我的代码中重复了以下模式:
class X<T, V>
{
V doTransform(T t) {
return null; // dummy implementation
}
Map<T, V> transform(List<T> item) {
return item.stream().map(x->new AbstractMap.SimpleEntry<>(x, doTransform(x))).collect(toMap(x->x.getKey(), x->x.getValue()));
}
}
要求使用 AbstractMap.SimpleEntry 是困惑和笨拙的。 Linq 对匿名类型的使用更加优雅。
是否有更简单的方法使用流来实现此目的?
提前致谢。
最佳答案
您可以在值映射器中调用doTransform
:
Map<T, V> transform(List<T> item) {
return item.stream().collect(toMap(x -> x, x -> doTransform(x)));
}
关于java - 使用 Java 流将列表转换为映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50671112/