distinct() Example



Example:
import java.util.Arrays;
import java.util.List;

public class DistinctFlight {
    public static void main(String[] args) {
        System.out.println("main() [Start]");


        List<Integer> numbers = Arrays.asList(6,10, 20, 10, 3, 3, 2, 4,6);
       
        numbers
        .stream()
        .filter(num->num%2==0)
        .distinct()
        .forEach(System.out::println);

       
        System.out.println("main() [End]");
    }
}


Ouput:
main() [Start]
6
10
20
2
4
main() [End]


Explanation:

 .filter(num->num%2==0) :
  • filter takes the lamda expression as an argument. 
  • It takes a lamda expression having functional interface having abstract method which take one argument and return boolean result. 
  • It returns the Stream of given type parameter. 
  .distinct():
  • this method works on the stream returned from the filter method
  • It returns the Stream with unique element.
  .forEach(System.out::println):
  • This method works on the stream returned from the distinct method
  • This is a terminal operation method because it doesnt return the stream.
  • All the previous streams maintained as pipeline and processed when this method get called
  • This method takes a consumer functional interface lamda expression or method reference as argument and it consumes the data of previous streams. Here it consumes and display each element.