0

I have a map in this format: Map<String, Map<Integer, Long>> and content like

{BCD={321=2}, ABC={123=1}, DEF={798=3}, CDE={564=1, 456=1}, GHI={908=2}}`

Is it possible sort the Long value reverse, then String and Integer?

Peter Walser
  • 15,208
  • 4
  • 51
  • 78
MIT
  • 109
  • 1
  • 7
  • Map is an unordered structure – Butiri Dan Jun 27 '19 at 12:00
  • 1
    What do you mean by "sort the long value reverse"? – Maurice Perry Jun 27 '19 at 12:27
  • It's not yet clear, what you are up to: You provide a datastructure which should be sorted. First question: what should be sorted? Please provide an example of the expected output. What entries should be eventually in the sorted array/list? Maybe you code an object which contains the named contents of your map to get a better understanding on your problem. – SirFartALot Jun 27 '19 at 12:29
  • can you please specify the excepted output in the Question? – dassum Jun 27 '19 at 12:29
  • Follow the https://stackoverflow.com/questions/33275195/sort-a-hashmap-inside-a-map-based-on-value – Vaibs Jul 02 '19 at 07:34

1 Answers1

1

No. You cannot sort contents of a Map.

Sorting is only possible on things, which retain a sorting, like List, TreeMap or TreeSet.

If you want the Map contents to be sorted, just implement a Comparator (e.g. Comparator<Map.Entry<String, Map<Integer, Long>>>) which is capable of returning an integer representing the order of two entries and feed all contents of your Map into a List<Map.Entry<String, Map<Integer, Long>>>, which can then be sorted.

   private static final Comparator<Map.Entry<String, Map<Integer, Long>>> COMPI = new Comparator<>() {
          @Override
          public int compare(Map.Entry<String, Map<Integer, Long>> obj1,
               Map.Entry<String, Map<Integer, Long>>(obj2)) {
                   ... return 0, if obj1 equal to obj2
                   ... return 1, if obj1 lower than obj2
                   ... return -1, if obj1 greater than obj2
          }

          public static List<Map.Entry<String, Map<Integer, Long>>> sortMyMap(Map<String, Map<Integer, Long>> myMap) {
                List<Map.Entry<String, Map<Integer, Long>>> l = new java.util.ArrayList<>(myMap.entrySet());
                Collections.sort(l, COMPI);
                return l;
           }
}

The most difficult part would be to implement the comparator correctly...

SirFartALot
  • 1,215
  • 5
  • 25
  • 3
    Or a `TreeMap` maybe? – rsp Jun 27 '19 at 12:03
  • 2
    Just as a note, there is the general interface `SortedMap` which sums up suchs maps, mainly consisting of `TreeMap`. Theres also `LinkedHashMap` which retains insertion order (but not general sorting). – Zabuzard Jun 27 '19 at 12:26
  • Well: ... and many other datastructures like Arrays, LinkedLists and other things. But especially a `java.util.Map` is not sortable per se, but only by transforming it somehow... – SirFartALot Jun 27 '19 at 12:36