15
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);

Desired output(HashMap):

c : 6
a : 4
b : 2

I haven't been able to find anything about Descending the order by value.
How can this be achieved? (Extra class not preferred)

10
  • 1
    You can't. But you can sort the Entries (once in a List or other ordered collection) by value: to start, List entries = new ArrayList<Entry<String,Integer>>(hash.getEntries()); then sort that. Commented Jan 10, 2014 at 21:09
  • @RC This is not the same question.. Commented Jan 10, 2014 at 21:13
  • 1
    (While I believe this is a "duplicate", the accepted answer in the other question is quite horrid - read over all the responses. I would also recommend using a [Array]List vs LinkedHashMap as the output collection.) Commented Jan 10, 2014 at 21:17
  • 1
    @GameDevGuru: Yes it is, except for trivial differences (map values being Strings instead of Integers). Read especially this answer. You could also have a look at this question: stackoverflow.com/questions/109383/… Commented Jan 10, 2014 at 21:18
  • I want a million dollars. No, make that 10 million. Commented Jan 10, 2014 at 21:18

3 Answers 3

31

Try this:

HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a, new Comparator() {
    public int compare(Object o1, Object o2) {
        return ((Map.Entry<String, Integer>) o2).getValue()
                   .compareTo(((Map.Entry<String, Integer>) o1).getValue());
    }
});
for (Object e : a) {
    System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : "
            + ((Map.Entry<String, Integer>) e).getValue());
}

output:

c : 6
a : 4
b : 2
Sign up to request clarification or add additional context in comments.

2 Comments

This puts the key,value pair as a single object in an array, I need to be able to retrieve the key, values seperately after sorting
It puts Map.Entry you can extract key and value from it separately, see upate
4

You can't explicity sort the HashMap, but can sort the entries. Maybe something like this helps:

// not yet sorted
List<Integer> intList = new ArrayList<Integer>(map.values());

Collections.sort(intList, new Comparator<Integer>() {

    public int compare(Integer o1, Integer o2) {
        // for descending order
        return o2 - o1;
    }
});

3 Comments

I believe the OP wants to have the key and value together, in however the result is used.
This separates the key from value, without the desired result..
This is true, I figured he was printing them out or something, so all he'd have to do then is make a method that calls map.getKey(value) and returns a string...or whatever he needs.
0

One of the characteristics of the Hash elements is their particular speed on doing operations like adding, deleting and so on, and this is precisely because they use Hash algorhythms, which means they doesn't keep the order of elements that we know as ascendant or descendant. That means that with the Hash data structures you won't achieve what you want.

5 Comments

It would be a very great suggestion to keep in mind however it does not answer the question.
Instead of saying it's impossible, how about suggesting to cast it as an ArrayList first..
@user2864740 List<String, Integer> intList = new ArrayList<String,Integer>(map); , and then working with the list. Or something to that effect.
@GameDevGuru But that's not a cast at all! For all casts in Java, where x is a reference type conforming to T: ((T)x) == x is true.
@user2864740 I have used the wrong terminology, i apologize for the confusion but I think you know what i meant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.