Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with LIst using Collectors.toMap in Java 8

I like convert below code to java stream,

HashMap<String, List<Data>> heMap = new HashMap<String, List<Data>>();
for (Data heData : obj) {
    String id = heData.getData().getId() + heData.getPlanData().getCode()
            + heData.getPlanData().getId();
    if (!heMap.containsKey(id)) {
        CitizenHElist = new ArrayList<Data>();

        CitizenHElist.add(heData);
        heMap.put(id, CitizenHElist);

    } else {
        heMap.get(id).add(heData);
    }
}

I tried the below code using stream, but i am not succeed on this.

heMap=obj.stream().collect(Collectors.toMap(t->getKey(t), obj.stream().collect(Collectors.toList())));

private String getKey(Data heData){
    String id = heData.getData().getId() + heData.getPlanData().getCode()
                    + heData.getPlanData().getId();
    return id;
}
like image 478
karthik selvaraj Avatar asked Dec 05 '22 18:12

karthik selvaraj


1 Answers

This is the job for groupingBy collector:

import static java.util.stream.Collectors.groupingBy;

Map<String, List<Data>> heMap = obj.stream().collect(groupingBy(d -> getKey(d)));

Note that this will use some unspecified implementations of Map and List. Currently, it happens to be HashMap and ArrayList, but that might change in the future.

like image 132
Misha Avatar answered Dec 09 '22 15:12

Misha