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

Time:11-12

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?

CodePudding user response:

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(","));
  • Related