【问题标题】:Java API Streams collecting stream in Map where value is a TreeSetJava API Streams 在 Map 中收集流,其中 value 是 TreeSet
【发布时间】:2018-02-04 14:47:14
【问题描述】:

有一个 Student 类,其中包含 name, surname, age 字段和 getter。

给定Student 对象流。

如何调用collect 方法,使其返回Map,其中键为Studentage,值为TreeSet,其中包含surname 的学生age

我想使用Collectors.toMap(),但卡住了。

我以为我可以这样做并将第三个参数传递给toMap方法:

stream().collect(Collectors.toMap(Student::getAge, Student::getSurname, new TreeSet<String>()))`.

【问题讨论】:

    标签: java java-8 java-stream collectors


    【解决方案1】:
    students.stream()
            .collect(Collectors.groupingBy(
                    Student::getAge,
                    Collectors.mapping(
                          Student::getSurname, 
                          Collectors.toCollection(TreeSet::new))           
    ))
    

    【讨论】:

      【解决方案2】:

      Eugene 提供了您想要的最佳解决方案,因为它是 groupingBy 收集器的完美工作。

      使用toMap 收集器的另一个解决方案是:

       Map<Integer, TreeSet<String>> collect = 
              students.stream()
                      .collect(Collectors.toMap(Student::getAge,
                              s -> new TreeSet<>(Arrays.asList(s.getSurname())),
                              (l, l1) -> {
                                  l.addAll(l1);
                                  return l;
                              }));
      

      【讨论】:

      • 当然,这个解决方案有效。然而,可变性会在并行期间导致线程安全问题?
      • @zikzakjack 不,这是完全线程安全的,每个线程都有自己的容器,稍后合并。
      • 我会将Arrays.asList 替换为Collections.singleton...
      猜你喜欢
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 2014-04-29
      • 2018-05-10
      • 2019-04-11
      相关资源
      最近更新 更多