使用流API查找列表中项目的所有索引
我正在尝试使用Java 8流和lambda表达式进行顺序搜索。 这是我的代码
List list = Arrays.asList(10, 6, 16, 46, 5, 16, 7); int search = 16; list.stream().filter(p -> p == search).forEachOrdered(e -> System.out.println(list.indexOf(e)));
Output: 2 2
我知道list.indexOf(e)
总是打印第一次出现的索引。 如何打印所有索引?
首先,使用Lambdas不是所有问题的解决方案……但是,即便如此,作为for循环,您也可以编写它:
List results = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { if (search == list.get(i).intValue()) { // found value at index i results.add(i); } }
现在,没有什么特别的错误,但请注意,这里的关键方面是指数,而不是价值。 索引是'loop'的输入和输出。
作为一个流::
List list = Arrays.asList(10, 6, 16, 46, 5, 16, 7); int search = 16; int[] indices = IntStream.range(0, list.size()) .filter(i -> list.get(i) == search) .toArray(); System.out.printf("Found %d at indices %s%n", search, Arrays.toString(indices));
产生输出:
Found 16 at indices [2, 5]