Sorting map by java value


There is map<Integer,Integer>, how do I sort it by value?

Author: Nicolas Chabanovsky, 2014-06-20

5 answers

Java 8

import java.util.Map;
import java.util.HashMap;

public class Main {
    public static void main(String[] args) { 
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(1, 10);
        map.put(2, 30);
        map.put(3, 50);
        map.put(4, 40);
        map.put(5, 100);
        map.put(6, 60);
        map.put(7, 110);
        map.put(8, 50);
        map.put(9, 90);
        map.put(10, 70);
        map.put(11, 80);

        map.entrySet().stream()
        .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed()) 
        .forEach(System.out::println); // или любой другой конечный метод
  }
}

Conclusion:

7=110
5=100
9=90
11=80
10=70
6=60
3=50
8=50
4=40
2=30
1=10
 13
Author: FORTRAN, 2017-05-11 20:20:02
    Map<Integer, Integer> map = new HashMap<>();
    List list = new ArrayList(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
        @Override
        public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) {
            return a.getValue() - b.getValue();
        }
    });
Исправил
 9
Author: ZingerCar, 2014-06-21 11:29:01

It is not so easy to write such a sorter right away. At least, I chose this strategy for myself in this case: write once, use many times. Therefore, I wrote such a sorter via Generics, because in map it can have other types as a key and value.

Below I will share two versions of the sorting method. For Java version = 7 and for Java version = 8.

So, if you have the 7th version of Java:

public static <K, V extends Comparable<? super V>> Map<K, V> 
    sortByValue(Map<K, V> map )
{
    List<Map.Entry<K, V>> list =
        new LinkedList<>(map.entrySet());
    Collections.sort( list, new Comparator<Map.Entry<K, V>>()
    {
        @Override
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2)
        {
            return (o1.getValue()).compareTo( o2.getValue() );
        }
    } );

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list)
    {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

That is, first, as @Nofate wrote, we pull out the list entries (this is our variable list), then we sort these entries by values and fill them into a new map (this is our result). For the resulting map, I used LinkedHashMap so that the elements are not re-sorted when added.

And here is the version using Stream's from Java 8:

public static <K, V extends Comparable<? super V>> Map<K, V> 
    sortByValue( Map<K, V> map )
{
      Map<K,V> result = new LinkedHashMap<>();
     Stream <Entry<K,V>> st = map.entrySet().stream();

     st.sorted(Comparator.comparing(e -> e.getValue()))
          .forEach(e ->result.put(e.getKey(),e.getValue()));

     return result;
}
 6
Author: VeLKerr, 2015-07-20 13:29:10

Making two ArrayLists with a key and a value. Parsing HashMap, immediately sorting by value.

    ArrayList<String> strings = new ArrayList<>();
    ArrayList<Float> floats = new ArrayList<>();

    for (HashMap.Entry<String, Float> e : map.entrySet()) {
        float value = e.getValue();
        boolean isAdded = false;
        for (int i = 0; i < floats.size(); i++) {
            if (value > floats.get(i)) {
                floats.add(i, value);
                strings.add(i, e.getKey());
                isAdded = true;
                break;
            }
        }
        if (!isAdded) {
            floats.add(value);
            strings.add(e.getKey());
        }
    }

    for (int i = 0; i < strings.size(); i++) {
        Log.d(TAG, "sort: " + strings.get(i) + "=" + floats.get(i));
    }

The output is sorted ArrayLists.

 0
Author: Alexey Che, 2018-02-25 08:44:47
TreeMap< String ,Integer> map= new TreeMap< String,Integer>();  
SortedMap<Integer, String> sortMapa = new TreeMap<Integer, String>(new IntegerComparator<Integer>());   
 Iterator<?> it = map.entrySet().iterator();     

 while(it.hasNext())
 {   @SuppressWarnings("unchecked")
    Entry< String ,Integer> En = (Entry<String, Integer>) it.next();    
    sortMapa.put( En.getValue(), En.getKey());

 }  

 Iterator<?> sortit = sortMapa.entrySet().iterator();    
 while(sortit.hasNext())
 {   @SuppressWarnings("unchecked")
    Entry< Integer,String > sEn = (Entry<Integer,String>) sortit.next();    
    System.out.println(sEn.getValue()+"-->"+sEn.getKey());       

 }  
 -1
Author: sergey krupnov, 2016-08-13 18:33:58