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
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))); }
Using parallel stream
private static Map<Integer, Boolean> convertUsingParallelStreams(List<Integer> numbers) { return numbers.parallelStream().collect(Collectors.toMap(e -> e, e -> isEven(e))); }
private static Boolean isEven(Integer number) { System.out.println(String.format("Current threadId : %s", Thread.currentThread().getId())); return number % 2 ==0; }
Output using stream –
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 –
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}