java - 如何在 Java 6 中等效于 Collectors.groupingBy?

标签 java grouping java-6

我有一个 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吗?以便我根据国家/地区的显示顺序进行显示。显示顺序为countryC=1,countryB=2 & countryA=3

比如我要显示

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

最佳答案

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

关于java - 如何在 Java 6 中等效于 Collectors.groupingBy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61119590/

相关文章:

android - 按文件夹分组布局 (Android)

postgresql - 比较表中的行对

Java 安全策略 : granting access depending on classloader

java - `javax.filter.Filter` 没有正确添加 CORS header

javascript - AngularJS 身份验证与 Spring Security CORS 问题

java - 在符号 ("@"处转换为 CharSequence

php - 使用正则表达式分组将搜索字符串转换为(我的)SQL where 子句

java - x64 Redhat 所需的 JDK 1.6 rpm

java.lang.ClassCastException : org. jboss.jca.adapters.jdbc.jdk6.WrappedConnectionJDK6 无法转换

Java 6,JFrame 始终停留在顶部