Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 381
VitalyT Avatar asked Jan 28 '23 16:01

VitalyT


1 Answers

You can do so with:

Comparator<MyState> comparator = Comparator.comparing(MyState::getDate)
                                        .thenComparing(MyState::getState);
map.values()
   .forEach(l -> l.sort(comparator));
like image 127
Ousmane D. Avatar answered Jan 31 '23 07:01

Ousmane D.