Sunday, 14 June 2020

Stream - filter(), map(), collect(), min(), max()


1) Filter:

filter() is used to filter data in stream. This method takes a Predicate as parameter. The Predicate interface contains a function called test() which the lambda expression passed as parameter is matched against. In other words, the lambda expression implements the Predicate.test() method.

stream.filter( item -> item.startsWith("o") ); 

It takes a single parameter and returns a boolean. If you look at the lambda expression above, you can see that it takes a single parameter item and returns a boolean - the result of the item.startsWith("o") method call.


2) Map:
map() is used to perform transformation for the items in a collection to other objects.

items.stream().map( item -> item.toUpperCase() )

In above stream items in stream is transformed to uppercase.

3) Collect:
when collect() method is invoked, the filtering and mapping will take place and the object resulting from those actions will be collected.

List<String> filtered = items.stream().filter( item -> item.startsWith("o") )
                                    .collect(Collectors.toList());

4) Min and Max:
The min() and max() methods take a Comparator as parameter. The Comparator.comparing() method creates a Comparator based on the lambda expression passed to it. In fact, the comparing() method takes a Function which is a functional interface suited for lambda expressions. It takes one parameter and returns a value.

The min() and max() methods return an Optional instance which has a get() method on, which you use to obtain the value. In case the stream has no elements the get() method will return null.

String shortest = items.stream()
        .min(Comparator.comparing(item -> item.length()))
        .get();

Inbuilt method:
List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4); 
  
/* Using stream.min() to get minimum element according to provided Integer Comparator */
Integer var = list.stream().min(Integer::compare).get(); 
System.out.print(var); 

No comments:

Post a Comment