Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Collectors.groupingBy equivalent in Java 6?

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
like image 753
StackUser321 Avatar asked Oct 22 '25 16:10

StackUser321


1 Answers

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());
like image 200
Olivier Grégoire Avatar answered Oct 25 '25 04:10

Olivier Grégoire