VitalyT
VitalyT

Reputation: 1691

how sort when hashmap value is list of objects by multiple properties java 8

Suppose I have like :

  Map<String, List<MyState>> map = new HashMap<>();
  map.computeIfAbsent(key, file -> new ArrayList<>()).add(myState);


  map.put("aa",list1..)
  map.put("bb",list2..)
  map.put("cc",list3..)

public class MyState {
    private String state;
    private String date;
}

I want to sort the map values List<MyState> by MyState::date and then by MyState::state

Upvotes: 4

Views: 1735

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56433

You can do so with:

Comparator<MyState> comparator = Comparator.comparing(MyState::getDate)
                                        .thenComparing(MyState::getState);
map.values()
   .forEach(l -> l.sort(comparator));

Upvotes: 8

Related Questions