1

I am trying to traverse a Hash map in decreasing order or in increasing order but I am not getting the proper output.

Here is my map:

Hashmap<String Integer> hm= new Hashmap<String,Integer>();

Here are my values:

Key    Value
Hi     4
kumar  1
Hello  1
vivek  3

I am trying something like:

List<Integer> ValueList = new ArrayList<Integer>(hm.values());
                ArrayList<String> keyList = new ArrayList<String>(hm.keySet());

Collections.sort(ValueList);
                Collections.reverse(keyList);
                Collections.reverse(ValueList);

and I want this something like:

Key    Value
kumar  1
Hello  1
vivek  3
Hi     4
Shakti Sharma
  • 2,131
  • 3
  • 18
  • 23
  • Post your code please. – Perdomoff Nov 19 '15 at 19:02
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – JFPicard Nov 19 '15 at 19:04
  • 1
    i have updated my code what i am trying – Shakti Sharma Nov 19 '15 at 19:05
  • You want to sort your hashmap based on numerical values? – Perdomoff Nov 19 '15 at 19:09
  • yes but i dont want to use that newmeric value as a key because there could be some duplicate value there – Shakti Sharma Nov 19 '15 at 19:12
  • 1
    possible duplicate of http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java – Atri Nov 19 '15 at 19:37
  • HashMap is not meant to store elements in ascending or descending order. See this [post](http://stackoverflow.com/a/10596272/4454454) – MaxZoom Nov 19 '15 at 20:10

3 Answers3

1

I recommend using the Apache Commons Collections ListOrderedMap. Here's the solution:

//Populate the map
Map<String, Integer> map = new HashMap<>();
map.put("Hi", 4);
map.put("kumar", 1);
map.put("Hello", 1);
map.put("vivek", 3);

//Sort the values
List<Integer> values = new ArrayList<Integer>(map.values());
Collections.sort(values);

int size = values.size();
Set<Entry<String, Integer>> entries = map.entrySet();

//Create a new ordered map
ListOrderedMap<String, Integer> orderedMap;
orderedMap = ListOrderedMap.listOrderedMap(new HashMap<String, Integer>(map));

for (int i = 0; i < size; i++) {

    Integer value = values.get(i);
    Iterator<Entry<String, Integer>> iter = entries.iterator();

    while (iter.hasNext()) {
        Entry<String, Integer> entry = iter.next();
        if (value.equals(entry.getValue())) {
            //Put all values at index i that match the value
            orderedMap.put(i, entry.getKey(), value);
        }
    }
}

//Print the orderedMap key/value pairs
entries = orderedMap.entrySet();
for (Entry<String, Integer> entry : entries) {
    final String key = entry.getKey();
    final Integer value = entry.getValue();
    System.out.println("key = " + key + ", value = " + value);
}

Output:

key = Hello, value = 1
key = kumar, value = 1
key = vivek, value = 3
key = Hi, value = 4
johnnieb
  • 3,982
  • 4
  • 29
  • 32
0

You can view a Map as a set of entries, where each entry has a key and a value. So what you want is a sorted list of entries. You can't just sort keys or values, as you would lose the association between the key and the value:

List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort(Comparator.comparing(Map.Entry::getValue));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

If you need to access these values often, you can avoid the sort by using a TreeMap object.

http://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html

This special Map can be used like a normal HashMap with the additional feature that it will sort your keys automatically using their Comparable, Equals and Hash methods (which you have to override)

If you define your own Key Class, you can make it so it will sort your values automatically.

If you don't need this performance boost, extracting the values then sorting them with Collections.sort works well too.

Guillaume F.
  • 5,905
  • 2
  • 31
  • 59