首页 > 解决方案 > 如何在 Java 6 中做 Collectors.groupingBy 等效?

问题描述

我有一个List<UserVO>
每个 UserVO 都有一个 getCountry()

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

我可以通过流来完成,但我必须在 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

标签: javagroupingjava-6

解决方案


这就是使用纯 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());

推荐阅读