JessicaDias
JessicaDias

Reputation: 41

How to sort a Map<String, List<Set<Long>>> by the Set size sum?

How can I sort a Map(String, List(Set(Long))) by the Set size sum? I have a HashMap like this:

myMap.put("monday", [[3215, 5654], [5345], [3246, 7686, 4565]]) // 6 Long elements in total
myMap.put("tuesday", [[3215, 5654], [5345, 2879, 6734], [3246, 7686, 4565]]) // 8 Long elements in total
myMap.put("wednesday", [[9845, 2521], [0954]]) // 3 Long elements in total

I expect the myMap sorted like this:

("tuesday", [[3215, 5654], [5345, 2879, 6734], [3246, 7686, 4565]]) // 8 Long elements in total
("monday", [[3215, 5654], [5345], [3246, 7686, 4565]]) // 6 Long elements in total
("wednesday", [[9845, 2521], [0954]]) // 3 Long elements in total

Upvotes: 4

Views: 271

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40048

Use LinkedHashMap for sorting:

Map<String, List<Set<Long>>> result = map.entrySet()
    .stream()
    .sorted(Comparator.comparingInt(e->e.getValue().stream().mapToInt(Set::size).sum()))
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

Upvotes: 5

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

You would be able to perform some operations on it, but keeping a HashMap sorted on value is indeed not possible.

However, if you know the operations you want to perform on it, you may use the following solution.

myMap.entrySet()
     .stream()
     .sorted((entry1, entry2) -> {
         Integer sum1 = getSumOfSetCount(entry1.getValue());
         Integer sum2 = getSumOfSetCount(entry2.getValue());
         return Integer.compare(sum1, sum2);
     })
     .forEach(entry -> // perform operation);

With getSumOfSetCount() being

public int getSumOfSetCount(List<Set<Long>> list) {
    return (int) list.stream()
                     .flatMap(Stream::of)
                     .count();
}

Upvotes: 1

Related Questions