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

点点圈 提交于 2019-12-17 18:44:56

问题


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?


回答1:


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 autoboxing is performed.

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);
}

but they didn't provide this identity method. Don't know why.




回答2:


An alternate way to transform that would be using Stream.flatMapToInt and IntStream.of as:

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.



来源:https://stackoverflow.com/questions/24633913/how-do-i-get-an-intstream-from-a-listinteger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!