简体   繁体   English

Java Map - 如何将自定义对象列表检索为单个列表

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

I have the following Java Map, where the values are lists of a custom type (EmployeeInfo):我有以下 Java Map,其中的值是自定义类型 (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!提前致谢!

You need to go through every key in myMap , and append every element in the current List to your result List .您需要遍历myMap每个键,并将当前List中的每个元素附加到您的结果List

List<EmployeeInfo> res = new LinkedList<>(); // Can be any list, not just linkedlist, but linkedlist works best for this.
for(List<EmployeeInfo> l : myMap.values()) {
    for(EmployeeInfo e : l) {
        res.add(e);
    }
}

Note: I made this on the stop in StackOverflow itself, so please fix any small syntax errors.注意:我在 StackOverflow 本身中停止了这个,所以请修复任何小的语法错误。

You need to convert the Map<String, List<EmployeeInfo>> or {[e1,e2], [e3,e4]} to List<EmployeeInfo> or [e1,e2,e3,e4] .您需要将Map<String, List<EmployeeInfo>>{[e1,e2], [e3,e4]}List<EmployeeInfo>[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

Like @Nishant Chatterjee KMS said, you need to flatten the values.就像@Nishant Chatterjee KMS 所说的那样,您需要扁平化这些值。

Here is a java 8 =< way of doing so:这是一个 java 8 ==< 这样做的方法:

Map<String, List<String>> foo = new HashMap<>();
List<String> bar = new ArrayList<>();
foo.values().forEach(bar::addAll);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM