0

The HashMap used is:

public static HashMap<User,Integer> onlineUsers = new HashMap<User,Integer>();

Lets say I add values like this:

onlineUsers.put(myUserObj,1);
onlineUsers.put(myUserObj,5);
onlineUsers.put(myUserObj,2);

How can I print the values out in descending order?

5
2
1

I've seen how do to this with a TreeMap but the Key in this case cannot be an integer.

ThatGuy343
  • 2,354
  • 3
  • 30
  • 55

5 Answers5

1

HashMap are only pairs of key/value and are in no way ordered.

However, it is possible to sort a Map by Value using a SortedSet of Map.entry see this post for how to do it TreeMap sort by value

Community
  • 1
  • 1
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
1

You can do this

// for each value
map.values()
   // sort them in reverse order
   .sort(Collections.reverseOrder())
   // and print each one
   .forEach(System.out::println);

Say you want to sort the keys by decreasing value. You can do this.

map.entrySet()
   .sort(Comparator.comparing(Map.Entry::getValue()).reversed())
   .map(Map.Entry::getKey())
   .forEach(System.out::println);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

A Map does not sort by values. Some of them (like TreeMap) sort by key, some of them (like HashMap) don't sort at all.

So what you need to do is get the Collection of values and sort those.

List<Integer> values = new ArrayList<>(map.values());
Collections.sort(values, Collections.reverseOrder())
Thilo
  • 257,207
  • 101
  • 511
  • 656
-1

Since as per you, treeMap is not an option, you can iterator through your hashmap and save the value in a temporary arrayList. Now use sort operation on that and then output the results.

Rusheel Jain
  • 843
  • 6
  • 20
-1

If you want to iterator in the order that you add the elements, you should use a LinkedHashMap.

The TreeMap is an ordered map. This implies that it uses the Comparable or Comparator interface to sort the elements. It sorts (and iterates) based on how it compares to other elements. The LinkedHashMap will sort based on the order that you insert the elements.

Isaiah van der Elst
  • 1,435
  • 9
  • 14