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

•

u/AutoModerator Dec 12 '20

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/[deleted] Dec 12 '20

This book helped me a lot.

1

u/King5lay3r Dec 12 '20

Thanks for the suggestion fellow reader. Will surely have a look.

2

u/[deleted] Dec 12 '20

I always recommend that editorial. I haven't read anything that it's not good (and usually they are better than just good).

This particular book covers from the (not so) new functional interfaces (including default methods), to lambdas, method references and streams.

Note aside, I just read your username. Jaime?

1

u/King5lay3r Dec 12 '20

I just read your username. Jaime?

YEAH!

brb having a Season 8 PTSD attack

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 :)

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.

2

u/MRH2 Intermediate Brewer Dec 12 '20

That's a great question. I have no idea either.