-1

I have a Map<String,List<UserVO>> studentsByCountry = new TreeMap<String,List<UserVO>>();

It displays like :

key=CountryA , value = List<UserVO>
key=CountryB , value = List<UserVO>
key=CountryC , value = List<UserVO>

Can I reshuffle this Map so that I display according to the displayOrder of the countries. Display order is countryC=1, countryB=2 & countryA=3. I want to display like

key=CountryC , value = List<UserVO>
key=CountryB , value = List<UserVO>
key=CountryA , value = List<UserVO>

One option is to append the sortOrderNumber to the key. For example 1_CountryC, 2_CountryB & 3_CountryA

Can I do it via conventional Java?

Harsh
  • 350
  • 1
  • 4
  • 13
  • 1
    How is the TreeMap supposed to know which goes first and which goes last? There is nothing in the key that suggests that CountryC should be the lowest element. – Juan Apr 30 '20 at 03:58
  • so appending with 1_, 2_, etc is the only option? – StackUser321 Apr 30 '20 at 04:05
  • No not the only one. But you need to have a rule to establish which is the order, and then implement that as a Comparator which you would pass into the contructor of the TreeMap. – Juan Apr 30 '20 at 04:15

1 Answers1

0

You should use new TreeMap<String, List<UserVO>>();

Map<String, List<UserVO>> sortedMap = new TreeMap<>(Collections.reverseOrder());
sortedMap.putAll(myMap);

Inspired from: Sorting Descending order: Java Map

If you want an unordered map you should use HashMap

TreeMap in Java is one of the implementations of the Map interface. How it differs from the other implementation HashMap is that unlike HashMap which is unordered, TreeMap is Sorted.

Harsh
  • 350
  • 1
  • 4
  • 13
  • .reverseOrder() means descending order. I want to keep it dynamic. So sometimes if sortOrder defined is DBAC, then we display: CountryD, CountryB, CountryA, CountryC – StackUser321 Apr 30 '20 at 04:11
  • [CountryD, CountryB, CountryA, CountryC] is not a sortOrder, you should implement HashMap. OR you need to add any prefix to define an order. – Harsh Apr 30 '20 at 04:16
  • yes, as I said, One option is to append the sortOrderNumber to the key. For example 1_CountryC, 2_CountryB & 3_CountryA – StackUser321 Apr 30 '20 at 07:57