dawit
dawit

Reputation: 205

Sorting a map based on multiple values(Java8/Jooq)

We had a data structure that looked something like this:

Map<String, Double> responseMap;

And were sorting this map in descending order based on value as:

responseMap.entrySet().stream()
        .sorted((Map.Entry.<String, Double>comparingByValue().reversed()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
                                      (e1, e2) -> e1, LinkedHashMap::new));

Now the data structure of this map changed to something like:

Map<String, Tuple2<Double, Integer> responseMap;  //org.jooq.lambda.tuple.Tuple2

How can we sort this map on the new value (based on the Double value and Integer) cleanly?

Upvotes: 3

Views: 195

Answers (1)

fps
fps

Reputation: 34460

You should simply change the comparator:

responseMap.entrySet().stream()
    .sorted(Comparator.comparing((Map.Entry<String, Tuple2<Double, Integer> e) -> 
                                  e.getValue().v1())
                      .thenComparing(e -> e.getValue().v2())
                      .reversed())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
                                  (e1, e2) -> e1, LinkedHashMap::new));

EDIT (as per the comments):

Alternatively, you can also use:

responseMap.entrySet().stream()
    .sorted(Comparator.comparing(Collections.reverseOrder(Map.Entry.comparingByValue(
            Comparator.comparing(Tuple2::v1).thenComparing(Tuple2::v2)))))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
                                  (e1, e2) -> e1, LinkedHashMap::new));

Upvotes: 4

Related Questions