4

I have a list of comma separated strings -

List: format = <unique id, label>
----- values -----
ab123,X
cd123,Y
ab123,Y
cd123,Z
------------------

I want to convert this list to Map<String, List<String>> using java 8 where key would be the unique id and value would be the list of labels (Map<unique-id, List<label>>).

Example -

Map[
ab123=List[X, Y],
cd123=List[Y, Z]
]

Could you please help me here so that I could implement this using java 8.

Also instead of Map, if I want to use dto class -

Class A {
 private String id;
 private List<String> labelList;
 // Getters and Setters methods
}

and I expect to create a list of class A, for example -

List[
A [id="ab123", labelList = List[X, Y],
A [id="cd123", labelList = List[Y, Z]
]

How could I get that?

bpa.mdl
  • 396
  • 1
  • 5
  • 19

2 Answers2

4
yourList.stream()
        .map(x -> x.split(",", 2))
        .collect(Collectors.groupingBy(
            x -> x[0],
            Collectors.mapping(x -> x[1], Collectors.toList())

));
Eugene
  • 117,005
  • 15
  • 201
  • 306
0

Using regex matching to filter all string that don't match given pattern:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ListToMapExample {

    public static void main(String[] args) {
        final List<String> list = Arrays.asList("ab123,X", "cd123,Y", "ab123,Y", "cd123,Z", "incorrect string", "", "a");
        final Pattern pattern = Pattern.compile("^([^,]+),(.*)$");

        final Map<String, List<String>> map = list.stream()
                .map(pattern::matcher)
                .filter(Matcher::matches)
                .collect(Collectors.groupingBy(
                        matcher -> matcher.group(1), 
                        Collectors.mapping(
                                matcher -> matcher.group(2), 
                                Collectors.toList()
                        ))
                );

        System.out.println(map);
    }
}

Output:

{cd123=[Y, Z], ab123=[X, Y]}
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131