3

I have a List<UserVO>
Each UserVO has a getCountry()

I want to group the List<UserVO> based on its getCountry()

I can do it via streams but I have to do it in Java6

This is in Java8. I want this in Java6

Map<String, List<UserVO>> studentsByCountry
= resultList.stream().collect(Collectors.groupingBy(UserVO::getCountry));

for (Map.Entry<String, List<UserVO>> entry: studentsByCountry.entrySet())
    System.out.println("Student with country = " + entry.getKey() + " value are " + entry.getValue());

I want output like a Map<String, List<UserVO>>:

CountryA - UserA, UserB, UserC
CountryB - UserM, User
CountryC - UserX, UserY

Edit: Can I further reschuffle this Map so that I display according to the displayOrder of the countries. Display order is countryC=1, countryB=2 & countryA=3

For example I want to display

CountryC - UserX, UserY
CountryB - UserM, User
CountryA - UserA, UserB, UserC

1 Answers1

4

This is how you do it with plain Java. Please note that Java 6 doesn't support the diamond operator so you have use <String, List<UserVO>> explicitly all the time.

Map<String, List<UserVO>> studentsByCountry = new HashMap<String, List<UserVO>>();
for (UserVO student: resultList) {
  String country = student.getCountry();
  List<UserVO> studentsOfCountry = studentsByCountry.get(country);
  if (studentsOfCountry == null) {
    studentsOfCountry = new ArrayList<UserVO>();
    studentsByCountry.put(country, studentsOfCountry);
  }
  studentsOfCountry.add(student);
}

It's shorter with streams, right? So try to upgrade to Java 8!

To have a specific order based on the reversed alphabetical String, as mentioned in the comments, you can replace the first line with the following:

Map<String,List<UserVO>> studentsByCountry = new TreeMap<String,List<UserVO>>(Collections.reverseOrder());
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
  • Edit: Can I further reschuffle this Map so that I display according to the displayOrder of the countries. Display order is countryC=1, countryB=2 & countryA=3 ======================================= For example I want to display CountryC - UserX, UserY | CountryB - UserM, UserN | CountryA - UserA, UserB, UserC – StackUser321 Apr 29 '20 at 16:54
  • Collections.reveseOrder() is to sort a list in descending order. I want in a specific order like C,B,A /// One option is to append the sortOrderNumber to the key. For example 1_CountryC, 2_CountryB & 3_CountryA – StackUser321 Apr 29 '20 at 17:45
  • 1
    This is outside the scope of your question. You should probably ask a new one. – Olivier Grégoire Apr 29 '20 at 19:08
  • ok done. https://stackoverflow.com/questions/61515600/how-to-change-the-sequence-of-entries-in-treemap-based-on-the-key – StackUser321 Apr 30 '20 at 03:48