Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use String::valueOf when joining a Set of Longs in Java 8?

I’m using Java 10. I have a java.util.Set of Longs. I would like to form a comma separated single String of my Set, so I tried

String concatenatedStr = setOfLongs.stream().mapToLong(String::valueOf).collect(Collectors.joining(","));

Sadly, this is throwing a couple of compilation errors, including "he type of valueOf(Object) from the type String is String, this is incompatible with the descriptor’s return type: long".

What’s the proper way to get a concatenated String from my Set of Longs?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

mapToLong() – is meant to produce a LongStream (a primitive stream) from a stream of objects. But it’s not the transformation you need in this case.

You need to turn a Stream<Long> into a Stream<String>, i.e. transform one stream of objects into another of objects. That requires map() operation, not mapToLong():

String concatenatedStr = setOfLongs.stream()
    .map(String::valueOf)
    .collect(Collectors.joining(","));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading