programmer
programmer

Reputation: 65

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

Upvotes: 2

Views: 76

Answers (1)

talex
talex

Reputation: 20455

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.

Upvotes: 4

Related Questions