假设我想转换一个 Set<Foo>
到 Map<Integer, Foo>
其中键对应于 Foo.hashCode()
我通常会按如下方式实现它:
Set<Foo> set = ...;
Map<Integer, Foo> map = set.stream()
.collect( Collectors.toMap( Object::hashCode,
element -> element )
);
element -> element
还有其他表达方式吗?在 java ?如果有,它们是什么?
最佳答案
您可以使用 Function.identity()
Map<Integer, Foo> map = list.stream()
.collect(Collectors.toMap(
Object::hashCode,
Function.identity()));
你可以静态导入它,然后你就有了
Map<Integer, Foo> map = list.stream()
.collect(Collectors.toMap(
Object::hashCode,
identity()));
关于java - lambda 表达式有多少种方式可以立即返回输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735125/