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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 13:35:27  来源:igfitidea点击:

How do I get an IntStream from a List<Integer>?

javacollectionsjava-8java-streamboxing

提问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::intValueis fully compatible with ToIntFunctionsince it takes an Integerand 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 barmethod :

我也在寻找等效的Function::identity,我希望编写等效的bar方法:

public static IntStream qux(List<Integer> list)
{
    return list.stream().mapToInt(IntFunction::identity);
}

but they didn't provide this identitymethod. Don't know why.

但他们没有提供这种identity方法。不知道为什么。

回答by Naman

An alternate way to transform that would be using Stream.flatMapToIntand IntStream.ofas:

另一种转换方法是使用Stream.flatMapToIntIntStream.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.

注意:在这里发帖之前,我已经解决了几个链接问题,但我也没有在其中找到建议。