如何在Java 6中实现Collectors.groupingBy等效?

问题描述 投票:0回答:1

我有一个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 - UserX, UserY
java grouping java-6
1个回答
0
投票

这是使用纯Java的方法。请注意,Java 6不支持Diamond运算符,因此您一直都在明确使用<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!

© www.soinside.com 2019 - 2024. All rights reserved.