我正在尝试使用.map和streams函数创建HashSet。
S是一个带有"id“参数的对象,Long类型。
这是我失败的尝试:
HashSet<Long> output = s.stream()
.map(v -> v.getId())
.collect(Collectors.toSet());
发布于 2019-06-27 03:08:50
在您的示例中,流的结果将是Set<Long>
,并且您希望将其赋给HashSet
类型的变量。因为HashSet
是Set
的一个子类型,所以您不能这样做。要么将输出变量的类型更改为Set<Long>
,要么将收集结果显式转换为HashSet<Long>
。因为Collectors::toSet
默认使用HashMap
,所以它应该可以工作。
编辑
正如shmosel正确指出的那样,假设返回类型可能不是一个好主意,所以如果你特别想要HashSet
,就使用toCollection(HashSet::new)
:
HashSet<Long> output = s.stream()
.map(v -> v.getId())
.collect(Collectors.toCollection(HashSet::new));
现在,collect
操作的结果将是HashSet<Long>
,因此您可以将其赋给HashSet<Long>
或Set<Long>
变量。
https://stackoverflow.com/questions/56779426
复制相似问题