java - 如何在 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
解决方案
这就是使用纯 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());
推荐阅读
- wordpress - 如何将域从 http 重定向到 https
- php - Laravel:迁移文件是否只在迁移和回滚之间运行一次?
- r - 是否可以将代码和绘图(从所述代码)导出为 r 中的 pdf?
- ubuntu - Ubuntu的一些键不起作用
- php - 插入视频后 div 布局发生变化
- c++ - 为什么引用不能与编译时函数一起使用?
- c# - Group Join 和 Orderby,同时保持之前的查询
- c++ - 将字符串转换为十六进制数组 C++
- authentication - Spring security自定义FilterInvocationSecurityMetadataSource实现403禁止问题
- asp.net-mvc - Ionic post API 错误未经授权