Java - 使用Stream展平嵌套映射

时间:2017-03-29 07:09:40

标签: java java-8 hashmap java-stream

我一直在搞乱Java 8 Stream API,遇到了一些我只能通过传统的for循环来做的事情。

给出

的嵌套地图
{
    1999: {
             3: [23, 24, 25],
             4: [1, 2, 3]
          },
    2001: {
             11: [12, 13, 14],
             12: [25, 26, 27]

          }
}

如何将其转换为

['23,3,1999', '24,3,1999', '25,3,1999', '1,4,1999', '2,4,1999', '3,4,1999', '12,11,2001', '13,11,2001', '14,11,2001', '25,12,2001', '26,12,2001', '27,12,2001']

基本上我想要复制:

    Map<Integer, Map<Integer, List<Integer>>> dates...
    List<String> flattened = new ArrayList<>();
    for (Integer key1 : map.keySet()) {
        for (Integer key2 : map.get(key1).keySet()) {
            for (Integer value : map.get(key1).get(key2)) {
                flattened.add(value + "," + key2 + "," + key1);
            }
        }
    }

3 个答案:

答案 0 :(得分:12)

试试这个例子:

year

如果您需要按month排序,那么day然后 dates.entrySet().stream().flatMap(year -> year.getValue().entrySet().stream().flatMap(month -> month.getValue().stream() .map(day -> Arrays.asList(year.getKey(), month.getKey(), day)))) .sorted(Comparator.comparing(l -> l.get(0)*10000 + l.get(1)*100 + l.get(2))) .forEach(System.out::println); 请尝试:

{{1}}

答案 1 :(得分:3)

 items
            .entrySet()
            .stream()
            .flatMap(
                    l-> l.getValue().entrySet().stream()
                            .flatMap(
                                    ll->ll.getValue().stream()
                                         .map(lll+","+ll.getKey()+","+l.getKey())))
            .collect(Collectors.toList())
            .forEach(System.out::println);

答案 2 :(得分:2)

假设有Holder可以采用3个整数,例如:

 static class Holder {

      private final int first;
      private final int second;
      private final int third;
 }

这些是一些嵌套的地图,然后2 flatMap将达到您想要的效果:

 List<Holder> holders = map.entrySet().stream().flatMap(
            e -> e.getValue()
                    .entrySet()
                    .stream()
                    .flatMap(x -> x.getValue().stream().map(y -> new Holder(e.getKey(), x.getKey(), y))))
            .collect(Collectors.toList());

    System.out.println(holders);