如何将嵌套映射转换为列表<object>

时间:2017-04-11 10:06:58

标签: java list hashmap

如何将嵌套地图转换为列表:

地图是:

Map<Integer, Map<Integer, Map<String, Double>>> list

Object类是:

public class employee {
private Integer id;
private Integer number;
private String  name;
private Double  salary;

如何将嵌套地图转换为List?

1 个答案:

答案 0 :(得分:3)

迭代地图条目。对于每个内部地图,还要迭代其条目等。对于最里面的地图中的每个条目,创建一个Employee并将其添加到列表中。

迭代地图的标准方法是迭代其入口集。 vefthym的答案向您展示如何使用for循环执行此操作。您可以将该代码用于您需要的内容。

如果您可以使用Java 8,您也可以使用流。我假设您的外部地图从ID映射到中间地图(我希望中间地图只包含一个条目;但我的代码也会或多或少地工作)。下一个地图从数字映射到从名称到工资的地图。

    List<Employee> empls = list.entrySet()
            .stream()
            .flatMap(oe -> oe.getValue()
                    .entrySet()
                    .stream()
                    .flatMap((Map.Entry<Integer, Map<String, Double>> me) -> me.getValue()
                            .entrySet()
                            .stream()
                            .map((Map.Entry<String, Double> ie)
                                    -> new Employee(oe.getKey(), me.getKey(), ie.getKey(), ie.getValue()))))
            .collect(Collectors.toList());

外部条目的意思是oe,即外部地图中的条目。类似地,me用于中间条目,ie用于内部条目。我已经将您的类重命名为以E开头,以遵循Java命名约定,并且我已经假设了一个方便的构造函数。

编辑:vefthym,你的答案现在在哪里,我指的是它?我知道你自己并不是很开心,这很公平。在任何情况下,使用for循环迭代地图的标准方法是:

    for (Map.Entry<Integer, String> currentEntry : yourMap.entrySet()) {
        // do your stuff here
        // use currentEntry.getKey() and currentEntry.getValue() to get the key and value from the current entry
    }

您需要在<>之后的Map.Entry中重复地图声明中的类型参数。

相关问题