Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to sort HashMap<String, String[]> by String in android
    primarykey
    data
    text
    <p>I have this code: </p> <pre><code> HashMap&lt;String, String[]&gt; unsorted = new HashMap&lt;String, String[]&gt;(); String[] values = new String[3]; String key; //add data to hashmap key = "abc"; values[0] = "a"; values[1]="b"; values[2]="c"; unsorted.put(key, values); key = "abc"; values[0] = "aa"; values[1]="bb"; values[2]="cb"; unsorted.put(key, values); key = "def"; values[0] = "d"; values[1]="e"; values[2]="f"; unsorted.put(key, values); //sort hashmap /***********/ //output should be: { abc-[a,b,c], abc-[aa,bb,cc], def-[d,e,f] } //or { abc-[aa,bb,cc], abc-[a,b,c], def-[d,e,f] } </code></pre> <p>How can I sort it like that? Note: I tried with using TreeMap, and other examples, but they eliminate the elements where the <em>keys</em> are equal.</p> <p><strong>Edit:</strong> I solved my problem :) thanks to Guillaume. Here is what I used:</p> <pre><code>import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class test { public static void main(String[] args) { ArrayList&lt;CustomObject&gt; objs = new ArrayList&lt;CustomObject&gt;(); objs.add(new CustomObject("abc", new String[] {"a", "b", "c"})); objs.add(new CustomObject("def", new String[] {"d", "e", "f"})); objs.add(new CustomObject("abc", new String[] {"aa", "bb", "cc"})); System.out.println(objs.isEmpty()); Collections.sort(objs, new Comparator&lt;CustomObject&gt;() { @Override public int compare(CustomObject o1, CustomObject o2) { int i = o1.getKey().compareTo(o2.getKey()); if(i == 0) return -1; return i; } }); for(int i=0; i&lt;objs.size(); i++) System.out.println("key/value pair:" + objs.get(i).getKey() + " - " + objs.get(i).getValues()[0]); } } </code></pre> <p>And the CustomObject:</p> <pre><code>public class CustomObject { private String key; private String[] values; public CustomObject(String key, String[] values) { this.key = key; this.values = values; } public String getKey() { return key; } public String[] getValues() { return values; } } </code></pre>
    singulars
    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