Skip to content
Advertisement

Java – how to improve on this function (Java 8 streams)

I’ve coded a function that finds the unique characters in a string using Java 8 streams, based on an example here.

To me, it’s pretty non-intuitive, maybe because I’m still learning streams. Is there any way to make this more readable?

Here’s the code:

JavaScript

Advertisement

Answer

For calculating the actual frequencies, you’re pretty much at a minimal example already!

JavaScript

And for doing it for a single string, it’s even easier (you save the conversions):

JavaScript

To that end, I would ensure that your code is simply consistent and readable. Use consistent indentation and comment how the stream steps per line, for example.

Edit: I’ve left the below (old) answer just to be informative for the OP, but it doesn’t answer the actual question.

Well, there’s always Stream#distinct.

Calcuating the “distinct” (not unique) characters:

JavaScript

If you want to avoid collecting it, you can also avoid all the hassle around the type boxing:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement