这是我第一次尝试使用 Java 1.8 中的新 Stream API,我不得不承认我在理解它时遇到了一些问题...
基本上,假设我有一个包含相同值的 int 数组。例如:
int[] intArray = new int[]{1,2,3,4,5};
现在,我想使用 Stream API 并将此 intArray 的索引存储在列表中,其中值大于 3。
这就是我的代码:
int[] intArray = new int[]{1,2,3,4,5};
List<Integer> indexes = IntStream.range(0, intArray.length)
.filter(i -> intArray[i] > 3)
.sorted()
.collect(Collectors.toList());
但是我收到编译失败消息,提示“IntStream 类型中的方法collect(Supplier, ObjIntConsumer, BiConsumer) 不适用于参数(Collector >)”。
我希望索引包含 3 和 4。
最佳答案
您应该将 IntStream
装箱进入Stream<Integer>
:
List<Integer> indexes = IntStream.range(0, intArray.length)
.filter(i -> intArray[i] > 3)
.sorted()
.boxed()
.collect(Collectors.toList());
关于java - 使用 Stream 时返回 Collection 中的数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33856271/