Transform a for iteration of a List<MutablePair> in a String with java 8

Viewed 113

How can I get the Left part of a MutablePair list with Java 8 - streams, forEach or something? The code I want to transform in Java 8 type is:

for (MutablePair<String, Long> id: list) {
   if (null == value) {
      value = id.getLeft();
   } else {
      value += ", " + id.getLeft();
   }
}

So, if I have the list as: [(OA,3853), (EE,866), (UN,728), (PP,10)], I need the value as: OA, EE, UN, PP as simple as possible. Many Thanks.

2 Answers

use map intermediate operation to transform to a Stream<String> then the joining collector to accumulate the elements into a single string separated by a ", " delimiter:

list.stream()
    .map(pair -> pair.getLeft()) // or MutablePair::getLeft
    .collect(Collectors.joining(", "));
list.stream()
    .map(MutablePair::getLeft)
    .collect(Collectors.joining(", "));

There are couple of other options for Collectors.joining Read more about it here

Related