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

4

u/wildjokers Dec 12 '20 edited Dec 12 '20

The biggest drawback to lambdas in java is the syntax is atrocious and having to use a single method interface as a header file is laughably bad.

This article is the best way to understand how to read the signatures, I was totally lost until I found this article (and I had been a java developer for 10 yrs when java 8 came out):

https://nofluffjuststuff.com/magazine/2016/09/time_to_really_learn_generics_a_java_8_perspective

No where in any kind of official JDK documentation does it ever mention that the generic types in the method signatures are the input and output parameter types for the lambda (if it has output). 💡

First half of the article is a nice review of generics, and even experienced java devs will probably learn something they didn’t know before there. The 2nd half covers how generics are used in the functional interface signatures. After you understand the signatures it is the just a matter of looking at the JavaDoc to see what is available in the API (the Stream API and Optional API).

As you can tell from your code example lambdas can become very unreadable very quickly. No one in their right mind would write code like that to count characters.

1

u/King5lay3r Dec 12 '20

The biggest drawback to lambdas in java is the syntax is atrocious and having to use a single method interface as a header file is laughably bad.

Truer words were never spoken.

Thanks for the article, will surely have a look.

2

u/nekokattt Extreme Brewer Dec 12 '20

Java needs to take a leaf of of Groovy and Kotlins book for lambda readability.

Kotlin's equivalent would be something like

Collectors.toMap(Int::toChar, { 1 }, Int::sum)

Ofc the lambda syntax collides with Java array literals, but you get the gist :)