Vikash Balasubramanian
Vikash Balasubramanian

Reputation: 3233

Java stream sorted not working

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

Upvotes: 1

Views: 4325

Answers (2)

Android Developer
Android Developer

Reputation: 466

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());
            }
        }
    }    

Upvotes: 2

Kayaman
Kayaman

Reputation: 73558

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

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

Upvotes: 5

Related Questions