1

I have a

HashMap<String,Integer> map 

which i want to sort in descending order by value I do:

HashMap<String,Integer> topSorted = new HashMap<>(); //sort map in descending order Stream<HashMap.Entry<String,Integer>> st = map.entrySet().stream(); st.sorted(Comparator.comparing((HashMap.Entry<String,Integer> e) -> e.getValue()).reversed()) .forEach(e -> topSorted.put(e.getKey(),e.getValue())); 

But topsorted is still the same as map no sorting is done at all

Can someone explain what i am doing wrong

1

2 Answers 2

5

HashMap is not ordered. You can't sort it.

You can use LinkedHashMap, which gives you a specific iteration order.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, you are correct i just forgot that HashMap is not ordered
2

Try this

public class OrderByValue { public static void main(String a[]){ Map<String, Integer> map = new HashMap<String, Integer>(); map.put("java", 20); map.put("C++", 45); map.put("Java2Novice", 2); map.put("Unix", 67); map.put("MAC", 26); map.put("Why this kolavari", 93); Set<Entry<String, Integer>> set = map.entrySet(); List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set); Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() { public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) { return (o2.getValue()).compareTo( o1.getValue() ); } } ); for(Map.Entry<String, Integer> entry:list){ System.out.println(entry.getKey()+" ==== "+entry.getValue()); } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.