如何从List <Integer>获取IntStream?

fre*_*low 40 java collections boxing java-8 java-stream

我可以想到两种方式:

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);
}
Run Code Online (Sandbox Code Playgroud)

什么是惯用的方式?也许已经有一个库函数完全符合我的要求?

gon*_*ard 46

我想(或者至少它是另一种选择)这种方式更具性能:

public static IntStream baz(List<Integer> list)
{
    return list.stream().mapToInt(Integer::intValue);
}
Run Code Online (Sandbox Code Playgroud)

由于该函数Integer::intValue完全兼容,ToIntFunction因为它需要一个Integer并返回一个int.没有执行自动装箱.

我也在寻找相同的Function::identity,我希望写一个相当于你的bar方法:

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

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

  • 什么自动装箱?在lambda版本中,x已经是一个Integer(来自List),并且使用intValue将"return x"隐式地_un_boxes它转换为int.我怀疑这种差异会在不知不觉中开始变小,并且在JIT通过它时会变小. (4认同)
  • 大声笑,我把`Integer :: valueOf`与`Integer :: intValue`混淆了.我建议的函数`foo`将列表中的Integer解包,将其传递给`valueOf`,然后将它返回到一个框中,然后再将它取消装箱*再放入流中:) (2认同)

Nam*_*man 6

另一种转换方法是使用Stream.flatMapToIntIntStream.of作为:

public static IntStream foobar(List<Integer> list) {
    return list.stream().flatMapToInt(IntStream::of);
}
Run Code Online (Sandbox Code Playgroud)

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