March 2018
Intermediate to advanced
208 pages
4h 52m
English
| | class Inventory { |
| | |
| | List<Supply> supplies = new ArrayList<>(); |
| | |
| | Map<String, Long> countDifferentKinds() { |
| | Map<String, Long> nameToCount = new HashMap<>(); |
| | |
| » | Consumer<String> addToNames = name -> { |
| | if (!nameToCount.containsKey(name)) { |
| | nameToCount.put(name, 0L); |
| | } |
| | nameToCount.put(name, nameToCount.get(name) + 1); |
| | }; |
| | |
| | supplies.stream() |
| | .filter(Supply::isUncontaminated) |
| | .map(Supply::getName) |
| » | .forEach(addToNames); |
| | return nameToCount; |
| | } |
| | } |
In the previous comparison Avoid Side Effects, we showed you how to turn a stream into a single long value with the reduce() operator and its special case, the count() operator. We’ve also hinted at the collect() operator. This ...