Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

java - Find all the indexes of an item within a list using stream API

I am trying sequential search using Java 8 streams and lambda expressions. Here is my code

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)));
Output: 2
        2

I know list.indexOf(e) always prints the index of the first occurrence. How do I print all the indexes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For a start, using Lambdas is not the solution to all problems... but, even then, as a for loop, you would write it:

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);
    }
}

Now, there's nothing particularly wrong with that, but note that the critical aspect here is the index, not the value. The index is the input, and the output of the 'loop'.

As a stream::

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));

Produces output:

Found 16 at indices [2, 5]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...