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

WDrgn :

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.

Ousmane D. :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306572&siteId=1