我有一个 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/