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

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


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


List<MyState>


MyState::date


MyState::state





Sorting map entries: HashMap is not ordered. Also, lists will have multiple entries. Which of the list elements do you use to sort values of the map itself?
– ernest_k
33 mins ago




map entries


HashMap





IMO the original post before the edit was more clear as it was stating you wanted to sort the map values by getDate then by getState. "I want to sort the map entries" no so clear.
– Aomine
31 mins ago




getDate


getState




1 Answer
1



You can do so with:


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





Should that be MyState::getState in the thenComparing block?
– christopher
33 mins ago


MyState::getState


thenComparing





@christopher yup, thanks.
– Aomine
32 mins ago





Or map.forEach((k, l) -> l.sort(yourComparator)) which I think should be faster.
– daniu
29 mins ago




map.forEach((k, l) -> l.sort(yourComparator))





@daniu yup that's also another way to go, but I simply avoided that since I am not interested in the map keys as I am sorting the lists.
– Aomine
28 mins ago








By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

wES Cnm,H1knAHDCpk8AIjIxjJYz RhCCX pPA5 oLxJl,dB66Niz1,O24nSmC08jx,29QxLnuzGLwBz UGvlVfkZmoo
L7hHzeupCxn 8 uKsdHiaJsA09m6h8h4hfUgKhW n,YWZn6rr5hxuAGQ

Popular posts from this blog

Visual Studio Code: How to configure includePath for better IntelliSense results

Spring cloud config client Could not locate PropertySource

Makefile test if variable is not empty