2

I want to sort HashMap < String[], Boolean > in ascending order. It works fine with this code which I have written

//HashMap<String[], Boolean> literalTable = new HashMap<>(); // declared some where in my code
ArrayList<String[]> arrayList = new ArrayList<>();
    for (int i = 0; i < literalTable.size(); ++i){
        String[] str = {};
        arrayList.add(str);
    }
    for (Map.Entry m: literalTable.entrySet()){
        String[] str = (String[]) m.getKey();
        Integer index = Integer.parseInt(str[0]);
        arrayList.set(index, str);
    }

    arrayList.sort(Comparator.comparing(p -> p[0]));

My question is, is there any sort way to do the same task? I Googled it and found one solution, it says that you can use TreeMap but it's not working as well.

Ajay Kumar
  • 115
  • 5
  • 10

1 Answers1

1

you need to pass the comparator to the TreeMap constructor to sort the array string

Map<String[], Boolean> hashMap = new HashMap<String[], Boolean>();
hashMap.put(new String[]{"bfa", "asdfs", "gr"}, true);
hashMap.put(new String[]{"efd", "asdfs", "gr"}, true);
hashMap.put(new String[]{"asd", "asdfs", "gr"}, true);
hashMap.put(new String[]{"bfd", "asdfs", "gr"}, true);

TreeMap<String[], Boolean> treeMap = new TreeMap<>(Comparator.comparing(a -> a[0]));
treeMap.putAll(hashMap);
treeMap.forEach((k, v) -> System.out.println(Arrays.toString(k) + " " + v));

output

[asd, asdfs, gr] true
[bfa, asdfs, gr] true
[bfd, asdfs, gr] true
[efd, asdfs, gr] true

You can try sort by the first element in key array, and use LinkedHashMap for maintaining the order

        LinkedHashMap<String[], Boolean> orderedMap = hashMap.keySet().stream()
                .sorted(Comparator.comparing(a -> a[0])) // ignore case if required
                .collect(Collectors.toMap(a -> a, a -> hashMap.get(a), (a, b) -> a, LinkedHashMap::new));
        orderedMap.forEach((k, v) -> System.out.println(Arrays.toString(k) + " " + v));

output

[asd, asdfs, gr] true
[bfa, asdfs, gr] true
[bfd, asdfs, gr] true
[efd, asdfs, gr] true

incase if you need to sort by the next element if first elements are matching you can concatinate the array to string and do sort

LinkedHashMap<String[], Boolean> orderedMap = hashMap.keySet().stream()
                .sorted(Comparator.comparing(a -> Arrays.toString(a))) // ignore case if required
                .collect(Collectors.toMap(a -> a, a -> hashMap.get(a), (a, b) -> a, LinkedHashMap::new));
Saravana
  • 12,647
  • 2
  • 39
  • 57