2

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 Answer 1

3

Use groupingBy:

Map<Integer, List<DataVO>> myDataMap =
    dataVoList.stream()
              .collect(Collectors.groupingBy(DataVO::getId));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.