How do I get an IntStream from a Listlt;Integergt;?(如何从 Listlt;Integergt; 中获取 IntStream?)
问题描述
我可以想到两种方法:
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);
}
什么是惯用的方式?也许已经有一个库函数可以完全满足我的要求?
What is the idiomatic way? Maybe there is already a library function that does exactly what I want?
推荐答案
我猜(或者至少是另一种选择)这种方式性能更高:
I guess (or at least it is an alternative) this way is more performant:
public static IntStream baz(List<Integer> list)
{
return list.stream().mapToInt(Integer::intValue);
}
由于函数 Integer::intValue 完全兼容 ToIntFunction 因为它需要一个 Integer 并返回一个 int.不执行自动装箱.
since the function Integer::intValue is fully compatible with ToIntFunction since it takes an Integer and it returns an int. No autoboxing is performed.
我也在寻找 Function::identity,我希望写一个与你的 bar 方法等效的方法:
I was also looking for an equivalent of Function::identity, i hoped to write an equivalent of your bar method :
public static IntStream qux(List<Integer> list)
{
return list.stream().mapToInt(IntFunction::identity);
}
但他们没有提供这个 identity 方法.不知道为什么.
but they didn't provide this identity method. Don't know why.
这篇关于如何从 List<Integer> 中获取 IntStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 List<Integer> 中获取 IntStream?
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
