How to sort HashMap by values?

HashMap<GridPane, Integer> hashmap = new HashMap<>(); 

enter image description here

Created TreeMap from LinkedHashMap, but swears on my design.

  • 2
    Sorting an ordinary HashMap does not work out, because this collection in its essence does not guarantee any order of keys / values. You should use a different type of data for storage, such as LinkedHashMap. If the task is not in the storage of values, please specify the question. - therainycat
  • one
    'List <Map.Entry <GridPane, Integer >> list = new ArrayList <> (map.entrySet ());' Instead of a treemap. You get the list of entries, and pass it to sort () - Maksim
  • GridPane in List <Map.Entry <GridPane, Integer >> list cannot eat. But String works. How it works I do not understand. - alex
  • Again, what does he write? - Maksim
  • Collections.sort accepts an object of type List as input, and you try to slip him a Map - temq

2 answers 2

Use Collections.sort(List<T> list, Comparator<? super T> c) .

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

You can get the List passing to the map.getEntrySet() constructor map.getEntrySet() After you get the sorted list, add each item in turn to the Map

  • And the map will remain the same order - temq
  • one
    Yes, you need to use LinkedHashMap at the end, it preserves the order in which the elements were added - Maksim
  • Even I have problems using this comparator. Help digest please. - alex
  • What problems? edit the question, it will be quite difficult without something concrete - Maksim
  • Thank you. LinkedHashMap saved, but I have not yet learned how to use the comparator) - alex

HasMap will not let you sort the elements inside you, because this is not an ordered collection and the location of the elements in it depends on their hashcodes. Use ThreeMap in the constructor of which you can pass a comparator that will produce a comparison of the elements. Sorting will be done by key.

  • Well, how to sort by value? TreeMap I made from LinkedHashMap. Apply the above construction does not work - alex
  • @alex According to the values ​​in any way, maybe some kind of another collection is needed in your situation and not a Map - temq