如何从列表中获取一个IntStream <Integer>? [英] How do I get an IntStream from a List<Integer>?
问题描述
我可以想出两种方式:
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);
}
什么是惯用的方式?
推荐答案
我想(或至少它是一个替代)这种方式更加高效:
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);
}
< com / javase / 8 / docs / api / java / lang / Integer.html#intValue--rel =nofollow> 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);
}
,但他们没有提供 code>方法。不知道为什么。
but they didn't provide this identity
method. Don't know why.
这篇关于如何从列表中获取一个IntStream <Integer>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!