gpt4 book ai didi

Java - 使用 Stream 展平嵌套 map

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:04:41 25 4
gpt4 key购买 nike

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

给定一个嵌套的 map

{
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);
}
}
}

最佳答案

例如试试这个:

public static void main(String[] args) {
Map<Integer, Map<Integer, List<Integer>>> dates =
new HashMap<Integer, Map<Integer, List<Integer>>>() {{
put(1999, new HashMap<Integer, List<Integer>>() {{
put(3, Arrays.asList(23, 24, 25));
put(4, Arrays.asList(1, 2, 3));
}});
put(2001, new HashMap<Integer, List<Integer>>() {{
put(11, Arrays.asList(12, 13, 14));
put(12, Arrays.asList(25, 26, 27));
}});
}};

dates.entrySet().stream().flatMap(year ->
year.getValue().entrySet().stream().flatMap(month ->
month.getValue().stream()
.map(day -> day + "," + month.getKey() + "," + year.getKey())))
.forEach(System.out::println);
}

如果您需要按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);

关于Java - 使用 Stream 展平嵌套 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43086667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com