r/javahelp • • Dec 12 '20

How do I master Java Streams/Functional Programming?

I was asked to count occurrences of each characters in a String using Java 8 Stream API and although I know basic operations in Streams I would have never guessed the following Collectors.toMap() solution;

Collectors.toMap(k -> Character.valueOf((char) k.intValue()),
		                v -> 1,         
		                Integer::sum)

How, and from where, do I learn such declarative functional programming so that I can know when to use what by looking at the problem?

19 Upvotes

12 comments sorted by

View all comments

12

u/desrtfx Out of Coffee error - System halted Dec 12 '20 edited Dec 12 '20

Learning streams is a mix of googling (StackOverflow) and practice, practice, practice.

The Advent Of Code competition that is currently ongoing is an excellent playground to learn these.

3

u/[deleted] Dec 12 '20

It's pretty early for me and I haven't had my coffee so I might be misreading but...

OP is creating a map of each character present on the String, while you're just counting a single character.

2

u/desrtfx Out of Coffee error - System halted Dec 12 '20

Yes, you're right. I misread OP's post.

Edited my post.