Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by values in HashMap class using Java

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());
                }
            }
        }
    }
}
like image 728
Ertuğrul Çetin Avatar asked Oct 04 '22 20:10

Ertuğrul Çetin


2 Answers

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());
    }
});
like image 192
Bhesh Gurung Avatar answered Oct 07 '22 18:10

Bhesh Gurung


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);
        }
      }
    }
  }
}
like image 42
swbock Avatar answered Oct 07 '22 20:10

swbock