mal*_*jun 16 java lambda list java-8
我正在尝试使用Java 8流和lambda表达式进行顺序搜索.这是我的代码
List<Integer> 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)));
Run Code Online (Sandbox Code Playgroud)
Output: 2
2
Run Code Online (Sandbox Code Playgroud)
我知道list.indexOf(e)
总是打印第一次出现的索引.如何打印所有索引?
rol*_*lfl 27
首先,使用Lambdas不是所有问题的解决方案......但是,即便如此,作为for循环,您也可以编写它:
List<Integer> 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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,没有什么特别的错误,但请注意,这里的关键方面是指数,而不是价值.索引是'loop'的输入和输出.
作为一个流::
List<Integer> 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));
Run Code Online (Sandbox Code Playgroud)
产生输出:
Found 16 at indices [2, 5]
Run Code Online (Sandbox Code Playgroud)