This is a part 1 of a series of posts I am planning to publish of Java Streams API, Predicates and Optional. Assumption here is you are starting off with Java 8 and are new to all these features. So the posts will start off with covering very basic concepts and then build upon them as we go along. I will also try to cover some other features in between involving method references, default methods, please read along and provide your feedback.
Streams
- Converting a list to a map
Assume we have a list of numbers and we want to return a map of number to boolean representing if the number is even or not. But this can be easily achieved using streams in a single line as well.
Using traditional forEach
private static Map<Integer, Boolean> convertWithoutUsingStreams(List<Integer> numbers) { Map<Integer, Boolean> map = new HashMap<>(); numbers.forEach(e -> map.put(e, isEven(e))); return map; }
Using streams instead
private static Map<Integer, Boolean> convertUsingStreams(List<Integer> numbers) {
return numbers.stream().collect(Collectors.toMap(e -> e, e -> isEven(e))); }
The benefits of using streams does not stop there. You can use parallel streams when dealing with large collections. Of course, you should make sure of using parallelism carefully.
Using parallel stream
private static Map<Integer, Boolean> convertUsingParallelStreams(List<Integer> numbers) { return numbers.parallelStream().collect(Collectors.toMap(e -> e, e -> isEven(e))); }
To see parallelism in action, take a look at this implementation of isEven method –
private static Boolean isEven(Integer number) { System.out.println(String.format("Current threadId : %s", Thread.currentThread().getId())); return number % 2 ==0; }
Output using stream –
As can be seen, the only thread being used is the main thread when using stream method on list.
Current threadId : 1 Current threadId : 1 Current threadId : 1 Current threadId : 1 Current threadId : 1 Current threadId : 1 Current threadId : 1 Current threadId : 1 Current threadId : 1 Current threadId : 1 Current threadId : 1 {100=true, 101=false, 102=true, 103=false, 104=true, 105=false, 106=true, 107=false, 108=true, 109=false, 110=true}
Output using parallelStreams –
In this case, the isEven method is getting invoked on various threads, including the main thread (threadId = 1).
Current threadId : 1 Current threadId : 9 Current threadId : 1 Current threadId : 9 Current threadId : 10 Current threadId : 9 Current threadId : 10 Current threadId : 9 Current threadId : 11 Current threadId : 10 Current threadId : 1 {100=true, 101=false, 102=true, 103=false, 104=true, 105=false, 106=true, 107=false, 108=true, 109=false, 110=true}