我有以下的Java地图,其中的值是一个自定义类型(EmployeeInfo)的列表:
Map<String, List<EmployeeInfo>> myMap;
我的目标是检索所有值从该映射一个单独的列表。到目前为止,我曾尝试以下,但没有取得它尚未工作:
// 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();
任何人都可以提供任何帮助吗?提前致谢!
您需要将转换Map<String, List<EmployeeInfo>>
或{[e1,e2], [e3,e4]}
到List<EmployeeInfo>
或[e1,e2,e3,e4]
。您可以通过平板映射值这样对列表。下面是使用流的方法:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句