Java 如何从 List<Integer> 获取 IntStream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24633913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get an IntStream from a List<Integer>?
提问by fredoverflow
I can think of two ways:
我可以想到两种方法:
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?
什么是惯用方式?也许已经有一个库函数可以完全满足我的要求?
采纳答案by gontard
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);
}
since the function Integer::intValue
is fully compatible with ToIntFunction
since it takes an Integer
and it returns an int
. No autoboxingis performed.
因为该函数Integer::intValue
是完全兼容的,ToIntFunction
因为它需要一个Integer
并且它返回一个int
。不执行自动装箱。
I was also looking for an equivalent of Function::identity
, i hoped to write an equivalent of your bar
method :
我也在寻找等效的Function::identity
,我希望编写等效的bar
方法:
public static IntStream qux(List<Integer> list)
{
return list.stream().mapToInt(IntFunction::identity);
}
but they didn't provide this identity
method. Don't know why.
但他们没有提供这种identity
方法。不知道为什么。
回答by Naman
An alternate way to transform that would be using Stream.flatMapToInt
and IntStream.of
as:
另一种转换方法是使用Stream.flatMapToInt
和IntStream.of
作为:
public static IntStream foobar(List<Integer> list) {
return list.stream().flatMapToInt(IntStream::of);
}
Note: Went through few linked questions before posting here and I just couldn't find this suggested in them either.
注意:在这里发帖之前,我已经解决了几个链接问题,但我也没有在其中找到建议。