This post will discuss how to find all occurrences of a value in a List in Java.

1. Using IntStream

To find an index of all occurrences of an item in a list, you can create an IntStream of all the indices and apply a filter over it to collect all matching indices with the given value. This is demonstrated below for a List of Integers:

Download  Run Code

Output:

[1, 4]

 
Note that we’re iterating over the range of the list’s indices, and not the actual list itself. The above solution returns a List, you can use the following solution to return an integer array:

Download  Run Code

Output:

[1, 4]

2. Using for loop

Here’s a version without Java Stream API, using a for loop. It can be used with Java 7 or earlier.

Download  Run Code

Output:

[1, 3]

That’s all about finding all occurrences of a value in a List in Java.