Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 355
WDrgn Avatar asked Dec 04 '25 12:12

WDrgn


1 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(", "));
like image 194
Ousmane D. Avatar answered Dec 07 '25 00:12

Ousmane D.