Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to get results HashMap sorted by value.

This is HashMap's keys and values:

map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);

I try to get results like this:

1 = can
2 = selin
4 = burak
5 = ertu

Here is my code:

import java.util.*;

public class mapTers {

    public static void main(String[] args) {

        HashMap<String, Integer> map = new HashMap<String, Integer>();

        map.put("ertu", 5);
        map.put("burak", 4);
        map.put("selin", 2);
        map.put("can", 1);

        Integer dizi[] = new Integer[map.size()];

        Set anahtarlar = map.keySet();

        Iterator t = anahtarlar.iterator();

        int a = 0;

        while (t.hasNext()) {
            dizi[a] = map.get(t.next());
            a++;
        }

        Arrays.sort(dizi);

        for (int i = 0; i < map.size(); i++) {
            while (t.hasNext()) {
                if (dizi[i].equals(map.get(t.next()))) {
                    System.out.println(dizi[i] + " = " + t.next());
                }
            }
        }
    }
}
share|improve this question
add comment

5 Answers

up vote 1 down vote accepted

Every time that you call t.next(), the iterator's pointer is moved forward. Eventually, the iterator reaches the end. You need to reset the iterator. Also, calling t.next() twice moves the pointer twice.

Here's my solution:

import java.util.*;
public class mapTers
{
  public static void main(String[] args)
  {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("ertu", 5);
    map.put("burak", 4);
    map.put("selin", 2);
    map.put("can", 1);
    Integer dizi[] = new Integer[map.size()];
    Set anahtarlar = map.keySet();
    Iterator t = anahtarlar.iterator();
    int a = 0;
    while (t.hasNext())
    {
      dizi[a] = map.get(t.next());
      a++;
    }
    Arrays.sort(dizi);
    for (int i = 0; i < map.size(); i++) 
    {
      t = anahtarlar.iterator();
      while (t.hasNext())
      {
        String temp = (String)t.next();
        if (dizi[i].equals(map.get(temp)))
        {
          System.out.println(dizi[i] + " = " + temp);
        }
      }
    }
  }
}
share|improve this answer
 
thank you so much –  neat159 Jun 14 '13 at 9:26
 
you're welcome :) –  swbock Jun 14 '13 at 16:30
add comment

You can sort the entries as follows (but note this won't sort the map itself, and also HashMap cannot be sorted) -

List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
    @Override
    public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
});
share|improve this answer
 
+1: You use Entry as the class that I proposed in my answer. Clever. –  SJuan76 Jun 14 '13 at 0:00
add comment

You cannot do that from a Map. At least not directly.

Retrieve the keys/entries, get all the map data in a more suitable structure (hint: a class that encapsulates both attributes and is is stored in a sortable (hint2: SortedSet, List)) and sort.

Do not forget to extend Comparable (and implement compareTo) or, otherwise, create a Comparator.

share|improve this answer
add comment

This is one of the solutions take from: http://stackoverflow.com/a/13913206/1256583

Just pass in the unsorted map, and you'll get the sorted one.

private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order) {

    List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

    // Sorting the list based on values
    Collections.sort(list, new Comparator<Entry<String, Integer>>() {
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            if (order) {
                return o1.getValue().compareTo(o2.getValue());
            }
            else {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}

To print, do a simple iteration over the entry set:

public static void printMap(Map<String, Integer> map) {
    for (Entry<String, Integer> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
    }
}
share|improve this answer
add comment

You probably have the wrong data structure for this problem. Either:

  1. Reverse the map so the integers are the keys and the words the values and make the map a SortedMap, or
  2. Use a bidirectional map as provided by libraries like Google Guava.

Reversed Map

private final SortedMap<Integer, String> TRANSLATIONS;
static {
    SortedMap<Integer, String> map = new TreeMap<>();
    map.put(1, "can");
    // ...
    TRANSLATIONS = Collections.unmodifiableSortedMap(map);
}

Guava BiMap

private final BiMap TRANSLATIONS =
   new ImmutableBiMap.Builder<String, Integer>()
        .put("ertu", 5);
        .put("burak", 4);
        .put("selin", 2);
        .put("can", 1);
        .build();

Then, iterate over a sorted version of the key set or value set as needed. For example,

TRANSLATIONS.inverse.get(4); // "burak"

I'm just curious. What language are your strings in?

share|improve this answer
 
Strings are Turkish :) –  Gökhan Girgin Jun 14 '13 at 0:12
 
Turkish--always the favorite example for people explaining String.toUpperCase(). –  Eric Jablow Jun 14 '13 at 0:28
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.