简体   繁体   English

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

[英]How can I sort a Map through the keyset?

I wanted to sort a Map through its keyset elements in a growing way. 我想以不断增长的方式通过其键集元素对地图进行排序。 The join type is innerJoin. 联接类型为innerJoin。 I have this code: 我有以下代码:

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

That returns this result: 返回结果:

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
...

And I wanted to get this result: 我想得到以下结果:

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
...

It is looks like you want to order by year then nation. 看来您想按年份再按国家订购。

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

EDIT Note that I use get1 then get0 while your code is using get0 then get1 . 编辑请注意,我用get1然后get0 ,而你的代码是使用get0然后get1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM