Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting HashMap values in Java not giving back right order
    primarykey
    data
    text
    <p>I am having some problem with sorting <code>HashMaps</code> with values in <code>Java</code>. My code is:</p> <pre><code> @SuppressWarnings("unchecked") Map&lt;String, Integer&gt; scores = ((HashMap&lt;String, Integer&gt;) prefs.get()); Map&lt;String, Integer&gt; sortedscores = sortByValues(scores); printMap(scores); System.out.println("=============="); printMap(sortedscores); </code></pre> <p>the prefs.get() returns a <code>Map&lt;String, ?&gt;</code> which I convert to <code>&lt;String, Integer &gt;</code></p> <p>The sorting function:</p> <pre><code>public static &lt;K, V extends Comparable&lt;V&gt;&gt; Map&lt;K, V&gt; sortByValues(final Map&lt;K, V&gt; map) { Comparator&lt;K&gt; valueComparator = new Comparator&lt;K&gt;() { public int compare(K k1, K k2) { int compare = map.get(k2).compareTo(map.get(k1)); if (compare == 0) return 1; else return compare; } }; Map&lt;K, V&gt; sortedByValues = new TreeMap&lt;K, V&gt;(valueComparator); sortedByValues.putAll(map); return new LinkedHashMap&lt;K,V&gt;(sortedByValues); } public static void printMap(Map&lt;String, Integer&gt; unsortMap){ for (Map.Entry entry : unsortMap.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } } </code></pre> <p>The output is:</p> <pre><code>Key : John Doe Value : 1000 Key : balazs Value : 975 Key : Balazs Value : 900 Key : aladar Value : 975 Key : balazs2 Value : 975 Key : score Value : 1000 Key : house Value : 1037 ============== Key : balazs Value : 975 Key : aladar Value : 975 Key : balazs2 Value : 975 Key : Balazs Value : 900 Key : house Value : 1037 Key : John Doe Value : 1000 Key : score Value : 1000 </code></pre> <p>The first one is the unsorted, the second is sorted. My problem is that the second output is not in DESC order (by value)</p> <p>EDIT: If I create a hasmap myself it works fine:</p> <pre><code>Map&lt;String, Integer&gt; unsortMap = new HashMap&lt;String, Integer&gt;(); unsortMap.put("asd", 1); unsortMap.put("asd2r1", 5); unsortMap.put("house", 7); unsortMap.put("3", 124); unsortMap.put("7", 4); unsortMap.put("5", 6); unsortMap.put("6", 2); unsortMap.put("8", 0); </code></pre> <p>But if I try it with this: <code>Map&lt;String, Integer&gt; scores = ((HashMap&lt;String, Integer&gt;) prefs.get());</code> I get that wierd order.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload