如何通过键集对地图排序?

时间:2019-05-15 09:24:23

标签: java java-stream

我想通过一种键集元素对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
...

1 个答案:

答案 0 :(得分:4)

您似乎想按年份然后按国家订购。

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

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