【问题标题】:Passing generic type to HashSet when doing collect收集时将泛型类型传递给 HashSet
【发布时间】:2017-04-13 18:27:34
【问题描述】:

假设我有一张公司部门地图到该部门的员工记录列表。

              Map<String, List<Employee>> departmentToEmployeesList = getMyMap();   

              Set<String> uniqueFirstNames = departmentToEmployeesList.
                    values()
                    .stream()
                    .collect(HashSet::new, HashSet::addAll, HashSet::addAll)
                    .stream()
                    .map(employee -> ((Employee)employee).getFirstName())
                    .collect(Collectors.toSet());

上面的代码有效,但我不想让((Employee)employee) 演员。如果没有强制转换,map 调用只会认为每个参数都是 Object 而不是 Employee

我们可以像这样把它分成两个调用:

                HashSet<Employees> flattenedEmployees = departmentToEmployeesList.
                    values()
                    .stream()
                    .collect(HashSet::new, HashSet::addAll, HashSet::addAll);

                Set<String> uniqueFirstNames = flattenedEmployees
                    .stream()
                    .map(Employee::getFirstName)
                    .collect(Collectors.toSet());

现在我们不必强制转换,HashSet 知道它的类型为Employee

有没有办法在collect 调用中将类型信息传递给HashSet::new?我是不是走错路了?

【问题讨论】:

  • 使用 flatMap 会更轻松高效:Set&lt;String&gt; uniqueFirstNames = departmentToEmployeesList.values().flatMap(List::stream).map(Employee::getFirstName).collect(toSet())
  • 但是你可以做 HashSet::new
  • 哎呀-不知何故我错过了!随时提交作为答案,我会将其标记为已解决。

标签: java-8 java-stream


【解决方案1】:

您可以使用HashSet&lt;Employee&gt;::new

但我宁愿重构您的代码以使用 flatMap:

Set<String> uniqueFirstNames = 
    departmentToEmployeesList.values()
        .stream()
        .flatMap(List::stream)
        .map‌​(Employee::getFirstN‌​ame)
        .collect(toSet()‌​);

【讨论】:

  • 我会根据你的建议进行重构。更有意义。
猜你喜欢
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
相关资源
最近更新 更多