gpt4 book ai didi

java - 如何通过键集对 map 进行排序?

转载 作者:行者123 更新时间:2023-11-30 06:41:11 24 4
gpt4 key购买 nike

我想以不断增长的方式通过其键集元素对 map 进行排序。连接类型是 innerJoin。我有这段代码:

Comparator<Tuple2<String, Integer>> comparator = Comparator.comparing((Function<Tuple2<String, Integer>, String>) Tuple2::get0).thenComparing(Tuple2::get1);

Map<Tuple2<String, Integer>, LongSummaryStatistics> grouped = join.stream()
.collect(groupingBy(t -> Tuples.of(t.get1().getCNation(), t.get4().getDYear()), () -> new TreeMap<>(comparator), summarizingLong(t->t.get0().getLoRevenue()-t.get0().getLoSupplycost())));

grouped.forEach((k, v) -> {
System.out.format("%-32s, %,d%n", k, v.getSum());
});

返回这个结果:

Tuple2Impl {ARGENTINA, 1992}    , 9.671.947.837
Tuple2Impl {ARGENTINA, 1993} , 10.047.205.160
Tuple2Impl {ARGENTINA, 1994} , 10.141.821.441
Tuple2Impl {BRAZIL, 1992} , 9.241.877.689
Tuple2Impl {BRAZIL, 1993} , 9.057.962.411
Tuple2Impl {BRAZIL, 1994} , 9.303.902.867
Tuple2Impl {CANADA, 1992} , 9.746.312.266
Tuple2Impl {CANADA, 1993} , 9.754.277.048
Tuple2Impl {CANADA, 1994} , 10.069.331.565
...

我想得到这个结果:

Tuple2Impl {ARGENTINA, 1992}    , 9.671.947.837
Tuple2Impl {BRAZIL, 1992} , 9.241.877.689
Tuple2Impl {CANADA, 1992} , 9.746.312.266
Tuple2Impl {ARGENTINA, 1993} , 10.047.205.160
Tuple2Impl {BRAZIL, 1993} , 9.057.962.411
Tuple2Impl {CANADA, 1993} , 9.754.277.048
Tuple2Impl {ARGENTINA, 1994} , 10.141.821.441
Tuple2Impl {BRAZIL, 1994} , 9.303.902.867
Tuple2Impl {CANADA, 1994} , 10.069.331.565
...

最佳答案

看起来你想按年份然后按国家排序。

Comparator<Tuple2<String, Integer>> comparator = 
Comparator.comparing((Function<Tuple2<String, Integer>, Integer>) Tuple2::get1)
.thenComparing(Tuple2::get0);

编辑请注意,我先使用 get1 然后使用 get0,而您的代码使用 get0 然后使用 get1

关于java - 如何通过键集对 map 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56145857/

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