Streams learning point
Mar. 13th, 2019 12:35 amYou can turn a Java
Getting a map of character counts:
Hmm, that's a lot of map-making boilerplate inside the collect bit. We can make it a
It's funny how the first example is now considered "boilerplate". Imagine doing it with anonymous inner classes instead of lambdas and method references.
It's also funny how chaining methods is the new normal. Some places where I worked would have to change their style guide.
String
into an IntStream
, but that's annoyingly different to a regular Stream
.Getting a map of character counts:
s.chars() .collect( HashMap<Integer,Integer>::new, (map, value)->{ Integer oldCount = map.get(value); map.put(value, null == oldCount ? 1 : oldCount + 1 ); }, HashMap::putAll )
Hmm, that's a lot of map-making boilerplate inside the collect bit. We can make it a
Stream<Integer>
and it's much simpler: s.chars() .boxed() // this bit makes collect easier .collect( Collectors.toMap( i->i, i->1, (i,b)->i+1 ) )
It's funny how the first example is now considered "boilerplate". Imagine doing it with anonymous inner classes instead of lambdas and method references.
It's also funny how chaining methods is the new normal. Some places where I worked would have to change their style guide.