Java 8 Stream (java.util.stream)
Stream :
A stream is not a data structure; it takes input from
underlying Collections, Arrays or any other objects. Stream work on underlying object
and don’t change the original object. There are various intermediate operations
on stream which returns a stream again. There is also terminal operation which
terminates the process and collect the result.
In a nut shell stream is wrapper around underlying data
which has multiple operation to allow process the bulk data operation easily.
Create stream;
1. We can create stream using collection.
Stream strm = listObject.stream();
2. Using array Object
Stream strm = Stream.of(array);
3. Using any String or Integer value.
Stream<Integer> strm = Stream.of(1,3,4,6,4);
4. We can create empty stream
Stream<String> emptyStream = Stream.empty();
5. Using Stream builder
Stream builder= Stream.builder();
Stream<String> strm = builder.add("A").build();
Intermediate operations
Java 8 stream has intermediate operations which return itself a stream. Intermediate operations don't get executed until terminal operations called. All Intermediate operations are lazy.
1. Stream filter( Predicate predicate)
example:
Stream strm = Stream.of(1,4,6,2,3);
Stream strm2 = strm.filter(value -> value >4)
long counter = strm2.count();
2. map function :
It returns a stream consisting of the results of replacing each element of the given stream with the contents of a mapped stream.
Suppose we have stream of Integer and we we want to convert each integer value multiply by 2.
We can achieve this using map().
List<Integer> list = Arrays.asList(5
,3,6,7);
list.stream().map(num -> num * 2
).forEach(System.out::println);
3.
flatmap :
flatmap() is a combination of map & flat operation, it applies function on element and flatterns them.
{ {1,2}, {3,4}, {5,6} } -> flatMap -> {1,2,3,4,5,6}
Terminal operation
1. collect :
Return the result of intermediate operation.
List<String> strm = Arrays.asList("one","two","three","four");
List<String> data = strm.stream().filter(s -> s.startsWith("o")).collect(Collectors.toList());
2. forEach :
Iterate through the elements in the stream
List<String> strm = Arrays.asList("one","two","three","four");
strm.stream().filter(s -> s.startsWith("o")).forEach(s -> System.out.println(s));
3. reduce :
Labels: collect, filter, flatmap, forEach, intermediate operation terminal operation, Java 8 stream, java.util.stream, map, reduce