2

I have a HashMap of arrays of strings identified by integers as key. I want to sort this HashMap by keys.

My hashmap : HashMap<Integer, String[]> htab = new HashMap<>();

I tried the TreeMap solution but it doesn't have a compatible constructor of my values (String[]): Map<Integer, String> map = new TreeMap<Integer, String>((Comparator<? super Integer>) htab);

Example of a set of my HashMap:

21 : {"2","3","5","10","0"}
roeygol
  • 4,908
  • 9
  • 51
  • 88
  • 2
    If the values are **arrays** of strings, use `Map = new TreeMap<>();` instead of `Map`. – Jesper Nov 29 '16 at 10:30
  • Yes, or: Map tmap = new TreeMap(Htab) – Maurice Perry Nov 29 '16 at 10:34
  • Or you can use **LinkedHashMap** and sort the instance of LinkedHashMap. This is a sample for how to sort a LinkedHashMap by value and sort by keys is the same. [link](http://stackoverflow.com/questions/12184378/sorting-linkedhashmap) – Ming Nov 29 '16 at 10:42

4 Answers4

1

You don't need the (Comparator<? super Integer>) part for your TreeMap. Also you have used String instead of String[] in your declaration. This code will work:

SortedMap<Integer, String[]> sortedMap = new TreeMap<Integer, String[]>(Htab);

Or alternatively you can declare Htab as a TreeMap instead of a HashMap to begin with.

Eddie Curtis
  • 1,207
  • 8
  • 20
0

If you want to sort the keys you may use a TreeSet or a TreeMap as follows. The keys are naturally sorted, i.e. the sorting is defined by the Integer class.

Map<Integer, String[]> map = new HashMap<>();

Set<Integer> naturallySortedKeys = new TreeSet<>(map.keySet());
Map<Integer, String[]> naturallySortedMap = new TreeMap<>(map);
Edo user1419293
  • 171
  • 2
  • 9
0

Just create the TreeMap with the HashMap as a parameter.

public void test() {
    Map<Integer, String[]> htab = new HashMap<>();
    String[] a = {"a", "3", "5", "10", "0"};
    htab.put(21, a);
    String[] b = {"b", "3", "5", "10", "0"};
    htab.put(210, b);
    String[] c = {"c", "3", "5", "10", "0"};
    htab.put(2, c);
    Map<Integer, String[]> sorted = new TreeMap<>(htab);
    System.out.println(htab);
    System.out.println(sorted);
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

You can use a TreeMap as per the comment written by jesper.

    Map<Integer, String[]> map = new TreeMap<Integer, String[]>();
    map.put(21, new String[] {"abc","bcde", "regweger"});
    map.put(43, new String[] {"dbc","bgercde", "reggweer"});
    map.put(31, new String[] {"afbc","bcdrge", "rewgwger"});
    map.put(5, new String[] {"abgc","bcdee", "regwesgr"});
    map.put(98, new String[] {"abhhc","bc3gde", "regrer"});
    map.put(11, new String[] {"awqbc","bc33de", "frgeger"});

    System.out.println(map.toString());

You will find the to string prints out the elements in ascending order of key value.

ArunTejCh
  • 81
  • 7