How to use multiple comparators on a map and property values ​​using Java 8

I have a card and you need to sort the key based on several conditions. How to achieve this with Java 8 Comparator and Stream?

class MyObject {
    private Set<Objects> setOfStuff;
    public Set<Objects> getSetOfStuff(){
        return listOfStuff;
    }
    public int countStuff(){
        return listOfStuff.size();
    }
}

Map<String, List<MyObject> needsSorting = new HashMap<>();
needsSorting.put("Monday", createSetOfObj());
needsSorting.put("Wednesday", createSetOfObj());
needsSorting.put("Thursday", createSetOfObj());

Set<MyObject> createSetOfObj() {
...
    return list;
}

Map<String, Set<MyObject>> sortedResult = new LinkedHashMap<>();
  • Sort by key, in alphabetical order
  • Sort by size List<MyObject>
  • Sort key based on the size of the largest MyObject countStuff();

if not, is there a better approach?

Update 1:

I think I have 1 and 2. Just not sure how to do this.

Comparator<Entry<String, List<MyObject>>> comparator = Comparator.comparing(Map.Entry<String, List<MyObject>>::getKey)
            .thenComparingInt(e -> e.getValue().size());

Update 2:

This is similar to what I need. I added countStuff for easy access to size.

Comparator<Entry<String, Set<MyObject>>> comparator = Comparator.comparing(Map.Entry<String, Set<MyObject>>::getKey)
            .thenComparingInt(e -> e.getValue().size())
            .thenComparingInt(e -> e.getValue().stream().map(MyObject::countStuff).max(Integer::max).get());
+4
source share
1 answer

HashMap , TreeMap :

SortedMap<String, List<MyObject>> sorted = new TreeMap<>(comparator);

: ,

+1

Source: https://habr.com/ru/post/1664001/


All Articles