【问题标题】:How to do Collectors.groupingBy equivalent in Java 6?如何在 Java 6 中做 Collectors.groupingBy 等效?
【发布时间】:2020-04-09 10:59:09
【问题描述】:

我有一个List<UserVO>
每个 UserVO 都有一个 getCountry()

我想根据getCountry()List<UserVO> 进行分组

我可以通过流来做到这一点,但我必须在 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&lt;String, List&lt;UserVO&gt;&gt;这样的输出:

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 grouping java-6


    【解决方案1】:

    这就是使用纯 Java 的方式。请注意,Java 6 不支持菱形运算符,因此您一直都明确使用 &lt;String, List&lt;UserVO&gt;&gt;

    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!

    如 cmets 中所述,要根据反转的字母字符串获得特定顺序,您可以将第一行替换为以下内容:

    Map<String,List<UserVO>> studentsByCountry = new TreeMap<String,List<UserVO>>(Collections.reverseOrder());
    

    【讨论】:

    • 编辑:我能否进一步重新调整此地图,以便根据国家/地区的 displayOrder 显示。显示顺序是 countryC=1, countryB=2 & countryA=3 ===================================== === 例如我想显示 CountryC - UserX, UserY |国家 B - 用户 M,用户 N | CountryA - 用户A、用户B、用户C
    • Collections.reveseOrder() 是对一个列表进行降序排序。我想要一个特定的顺序,比如 C、B、A /// 一种选择是将 sortOrderNumber 附加到键上。例如 1_CountryC、2_CountryB 和 3_CountryA
    • 这超出了您的问题范围。你可能应该问一个新的。
    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 2017-02-08
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    相关资源
    最近更新 更多