Java Collection Stream

Java Collection Stream was presented in Java 8. 


Creation

Create stream much the same as getting iterator from collection

 Stream<> stream = collection.stream();

 Stream<> stream = collection.parallelStream();

Stream.filter()


You filter a stream using the filter() method. 

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


Stream.map()

It is possible to map the items in a collection to other objects. 

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

Stream.collect()


When this 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());

Stream.min() and Stream.max()


Once these are called, the stream will be iterated, filtering and mapping applied, and the minimum or maximum value in the stream will be returned.

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

The min() and max() methods return an Optional instance.

Stream.count()


The count() method simply returns the number of elements in the stream after filtering has been applied.

long count = items.stream()
     .filter( item -> item.startsWith("t"))
     .count();

Stream.reduce()


The reduce() method can reduce the elements of a stream to a single value. 

String reduced2 = items.stream()
        .reduce((acc, item) -> acc + " " + item)
        .get();

The reduce() method takes a BinaryOperator as parameter, which can easily be implemented using a lambda expression. The BinaryOperator.apply() method is the method implemented by the lambda expression above. This method takes two parameters. The acc which is the accumulated value, and itemwhich is an element from the stream. 
The reduce() method taking a BinaryOperator as parameter returns an Optional . 
There is another reduce() method which takes two parameters. It takes an initial value for the accumulated value, and then a BinaryOperator.
String reduced = items.stream()
        .reduce("", (acc, item) -> acc + " " + item);

Comments

Popular posts from this blog

Getter Template with Optional<> for IntelliJ IDEA

JVM Memory and Tuning

Inversion of Control - Pattern