Java 8 Stream API

Why Streams

  • If you are looping collection to run specific operation, streams is the solution
  • Process computations on large collections with less code, in parallel and efficiently

Streams

  • Stream is like pipeline of sequence of elements from a source (e.g. collections) that supports aggregate operations (e.g. filter, map, reduce, find, sorted, match)
  • Most of Stream operations returns Stream. Therefore multiple operations can be chained
  • Stream library uses internal iteration during on demand computation

Example

Extract even numbers; times 2 each; and order in descending order
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
List<Integer> computedNumbers = numbers.stream()
		.filter(n -> {
			return n % 2 == 0;
			})
		.map(n -> {
			System.out.println("mapping " + n);
			return n * 2;
			})
		.sorted((a, b) -> b.compareTo(a))
		.collect(Collectors.toList());
System.out.println(computedNumbers);

Output
mapping 2
mapping 4
mapping 6
mapping 8
[16, 12, 8, 4]
  • stream() makes pipeline
  • .filter(Predicate<?>) extracts according to Lambda expression and returns Stream
  • .sorted(Predicate<?>) sorts according to Comparator provided as Lambda expression
  • Finally, used collect to retrieve as List. It is one of terminal operation used to close Stream pipeline

Resources

Leave a Reply

Your email address will not be published. Required fields are marked *