[英]How to do Collectors.groupingBy equivalent in Java 6?
I have a List<UserVO>
我有一个
List<UserVO>
Each UserVO has a getCountry()每个 UserVO 都有一个 getCountry()
I want to group the List<UserVO>
based on its getCountry()
我想根据它的
getCountry()
对List<UserVO>
进行分组
I can do it via streams but I have to do it in Java6我可以通过流来完成,但我必须在 Java6 中完成
This is in Java8.这是在Java8中。 I want this in Java6
我想要这个在 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());
I want output like a Map<String, List<UserVO>>
:我想要 output 像
Map<String, List<UserVO>>
:
CountryA - UserA, UserB, UserC
CountryB - UserM, User
CountryC - UserX, UserY
Edit: Can I further reschuffle this Map
so that I display according to the displayOrder of the countries.编辑:我可以进一步重新调整这个
Map
以便我根据国家的 displayOrder 显示。 Display order is countryC=1, countryB=2 & countryA=3显示顺序为 countryC=1, countryB=2 & countryA=3
For example I want to display例如我想显示
CountryC - UserX, UserY
CountryB - UserM, User
CountryA - UserA, UserB, UserC
This is how you do it with plain Java.这就是使用普通 Java 的方法。 Please note that Java 6 doesn't support the diamond operator so you have use
<String, List<UserVO>>
explicitly all the time.请注意,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);
}
It's shorter with streams, right?流更短,对吧? So try to upgrade to Java 8!
所以尝试升级到Java 8!
To have a specific order based on the reversed alphabetical String, as mentioned in the comments, you can replace the first line with the following:如评论中所述,要根据反向字母字符串获得特定顺序,您可以将第一行替换为以下内容:
Map<String,List<UserVO>> studentsByCountry = new TreeMap<String,List<UserVO>>(Collections.reverseOrder());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.