我可以想到两种方法:
public static IntStream foo(List<Integer> list)
{
return list.stream().mapToInt(Integer::valueOf);
}
public static IntStream bar(List<Integer> list)
{
return list.stream().mapToInt(x -> x);
}
惯用的方式是什么?也许已经有一个库函数可以做我想要的事情了?
发布于 2014-07-08 22:40:19
我猜(或者至少它是另一种选择)这种方式性能更好:
public static IntStream baz(List<Integer> list)
{
return list.stream().mapToInt(Integer::intValue);
}
因为函数Integer::intValue
与ToIntFunction
完全兼容,因为它接受一个Integer
并返回一个int
。不执行autoboxing。
我也在寻找一个等价的Function::identity
,我希望写一个等价于你的bar
方法的东西:
public static IntStream qux(List<Integer> list)
{
return list.stream().mapToInt(IntFunction::identity);
}
但是他们没有提供这个identity
方法。不知道为什么。
https://stackoverflow.com/questions/24633913
复制相似问题