java - How can I sort a Map according to the parameters of its values? -
this question has answer here:
- sort map<key, value> values (java) 44 answers
stream<map.entry<string, list<object>>> sorted = index.entryset().stream() .sorted(map.entry.comparingbyvalue());
the method
sorted(comparator<? super map.entry<string,list<nfarticle>>>)
in typestream<map.entry<string,list<nfarticle>>>
not applicable arguments(comparator <map.entry<object,comparable<? super comparable<? super v>>>>)
i want sort hashmap
according size()
of lists being values of hashmap
. how can achieve using stream library java 8?
this may helpful you.
i changed type of result map linkedhashmap respect insertion order.
public static void main(string[] args) { final map<string, list<integer>> map = new hashmap<>(); map.put("k1", arrays.aslist(new integer[]{1, 2, 3, 4, 5})); map.put("k2", arrays.aslist(new integer[]{1, 2, 3, 4, 5, 6})); map.put("k3", arrays.aslist(new integer[]{1, 2, 3})); system.out.println(getmapsortedbylistsize(map)); } public static <k, v> map<k, list<v>> getmapsortedbylistsize(final map<k, list<v>> map) { return map.entryset().stream() .sorted((e1, e2) -> e1.getvalue().size() - e2.getvalue().size()) .collect(collectors.tomap(map.entry::getkey, map.entry::getvalue, (a, b) -> a, linkedhashmap::new)); }
Comments
Post a Comment