Java Map - How to retrieve list of custom objects as a single list

fittaoee :

I have the following Java Map, where the values are lists of a custom type (EmployeeInfo):

Map<String, List<EmployeeInfo>> myMap;

My goal is to retrieve all the values as one single List from this map. So far I have tried the following, but haven't made it work yet:

// ERROR: The constructor ArrayList<EmployeeInfo>(Collection<List<EmployeeInfo>>) is undefined
List<EmployeeInfo> info = new ArrayList<EmployeeInfo>(myMap.values());

// ERROR: java.lang.ClassCastException: java.util.HashMap$Values cannot be cast to java.util.List
List<EmployeeInfo> info = (List)myMap.values();

Could anyone provide any help? Thanks in advance!

Sam :

You need to convert the Map<String, List<EmployeeInfo>> or {[e1,e2], [e3,e4]} to List<EmployeeInfo> or [e1,e2,e3,e4]. You can do this by flat mapping the values to list. Here is a approach using streams:

List<EmployeeInfo> list = myMap.values() // gives you [[e1,e2],[e3,e4]]
                               .stream() // stream over them
                               .flatMap(List::stream) // convert to [e1,e2,e3,e4]
                               .collect(Collectors::toList); // collect back

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345745&siteId=1