Java8 Streams
February 22, 2017 Leave a comment
Streams are functional programming design pattern for processing of elements of a data structure sequentially or parallely.
Example:
List<Order> orders = getOrders(); int qtySum = orders.stream() .filter(o -> o.getType().equals("ONLINE")) .mapToInt(o -> o.getQuantity()) .sum();
Above code can be explained as below:
- Create a stream from source java collection
- Add a filter operation to the stream “intermediate operations pipeline”
- Add a map operation to the stream “intermediate operations pipeline”
- Add a terminal operation that kicks off the stream processing
A Stream has
- Source: that stream can pull objects from
- Pipeline: of operations that can execute on the elements of the stream
- Terminal: operation that pull values down the stream
Streams are lazily evaluated and the stream lifecycle is
- Creation: from source
- Configuration: from collection of pipeline operations
- Execution: (terminal operation is invoked)
- Cleanup
Few java stream sources
// Number Stream LongStream.range(0, 5).forEach(System.out::println) // Collection Streams List<String> cities = Arrays.asList("nyc", "edison", "livingston"); cities.stream().forEach(System.out::println) // Character Srream int cnt = "ABC".chars().count() // File Streams Path filePath = new Path("/user/ntallapa/test"); Files.list(filePath).forEach(System.out::println);
Stream Terminal Operations
- Reduction Terminal Operations: results in single result
- reduce(f(x)), sum(f(x)), min(f(x)), max(f(x)), etc
- Mutable Reduction Terminal Operations: returns multiple results in a container data structure
- List integers = Arrays.asList(1,2,3,3);
- Set integersSet = integers.stream().collect(Collectors.toSet()); // returns 1,2,3
- Search Terminal Operations: returns result as soon as match is found
- findFirst(), findAny(), anyMatch(f(x))
- Generic Terminal Operations: do any kind of processing on every element
Stream Pipeline Rule: Since streams are meant to process elements sequentially/parallely, stream source is not allowed to modify
Intermediate Pipeline operations can be of two types
- Stateless: filter(f(x)), summaryStatistics()
- Statefull: distinct(), limit(n), skip(n)
References:
https://www.youtube.com/watch?v=MLksirK9nnE
https://www.youtube.com/watch?v=8pDm_kH4YKY
Recent Comments