5

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

5 Answers 5

2

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());
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

+1: You use Entry as the class that I proposed in my answer. Clever.
1

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

Comments

1

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.

Comments

0

This is one of the solutions take from: https://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());
    }
}

Comments

0

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?

1 Comment

Turkish--always the favorite example for people explaining String.toUpperCase().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.