如何在Java 6中实现Collectors.groupingBy的功能?

3

我有一个 List<UserVO>

每个UserVO都有一个getCountry()方法

我想根据它的getCountry()List<UserVO>进行分组

我可以使用流来实现,但我必须在Java6中完成

以下是Java8代码,我想在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());

我希望得到类似于 Map<String, List<UserVO>> 的输出结果:
CountryA - UserA, UserB, UserC
CountryB - UserM, User
CountryC - UserX, UserY

编辑:我是否可以进一步重排这个Map,以便按照国家的displayOrder显示。 显示顺序为countryC = 1,countryB = 2和countryA = 3。

例如,我想要显示:

CountryC - UserX, UserY
CountryB - UserM, User
CountryA - UserA, UserB, UserC
1个回答

4

以下是使用普通Java实现的方法。请注意,Java 6不支持钻石操作符,因此您必须始终明确地使用<String,List<UserVO>>

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);
}

使用流可能会更简洁,所以尝试升级到Java 8版本!

如评论中所述,如果要根据反向字母表字符串的特定顺序排序,则可以将第一行替换为以下内容:

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

例如,我想按以下顺序显示:CountryC - UserX,UserY | CountryB - UserM,UserN | CountryA - UserA,UserB,UserC可以进一步重排这个Map,以便根据国家的displayOrder进行显示。其中,CountryC=1,CountryB=2,CountryA=3。 - StackUser321
Collections.reverseOrder()是用于将列表按降序排序的方法。我想按照特定顺序排序,如C、B、A。/// 一种选项是将sortOrderNumber附加到键上。例如1_CountryC、2_CountryB和3_CountryA。 - StackUser321
1
这超出了你的问题范围。你可能应该提一个新问题。 - Olivier Grégoire
好的,完成。 - StackUser321

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接