Find all occurrences of a value in a List in Java
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; class Main { public static void main(String[] args) { List<Integer> values = List.of(1, 3, 5, 2, 3, 4, 6); int item = 3; List<Integer> indices = IntStream.range(0, values.size()) .filter(i -> Objects.equals(values.get(i), item)) .boxed().collect(Collectors.toList()); System.out.println(indices); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.IntStream; class Main { public static void main(String[] args) { List<Integer> values = List.of(1, 3, 5, 2, 3, 4, 6); int item = 3; int[] indices = IntStream.range(0, values.size()) .filter(i -> Objects.equals(values.get(i), item)) .toArray(); System.out.println(Arrays.toString(indices)); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.ArrayList; import java.util.List; import java.util.Objects; class Main { public static void main(String[] args) { List<String> values = List.of("A", "B", "C", "B"); String item = "B"; List<Integer> indices = new ArrayList<>(); for (int i = 0; i < values.size(); i++) { if (Objects.equals(values.get(i), item)) { indices.add(i); } } System.out.println(indices); } } |
Output:
[1, 3]
That’s all about finding all occurrences of a value in a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)