Java - Convert List into Map & merge duplicate key data internally

Viewed 62

I've List containing data a VO, say DataVO like:

DataVO 1: 1, abcd, efgh
DataVO 2: 1, pqrs, wxyz
DataVO 3: 2, hello, letsgo

I want to create a Map with key as first element and the List as the value.

Map<Integer, List<DataVO>> myDataMap

So the contents will be like:

myDataMap.get(1) is List containing 1, abcd, efgh & 1, pqrs, wxyz

myDataMap.get(2) is List containing 2, hello, letsgo

Right now I'm doing it like this:

Map<Integer, List<DataVO>> myDataMap = new HashMap<>();
dataVoList.forEach(dataVo -> {
    int id = dataVo.getId();
    if (myDataMap.containsKey(id)) {
        myDataMap.get(id).add(dataVo);
    } else {
        myDataMap.put(id, new ArrayList<>(Arrays.asList(dataVo)));
    }
});

How to optimize this?

I tired using stream, like this:

dataVoList.stream().collect(toMap(Data::id, ....));

But it gives duplicate key error.

And if I use merge attribute, then it only keeps one element. (As explained here)

Please suggest.

1 Answers

Use groupingBy:

Map<Integer, List<DataVO>> myDataMap =
    dataVoList.stream()
              .collect(Collectors.groupingBy(DataVO::getId));
Related