I'm trying to search an ArrayList
for a user input. I've managed to create a search that prints the index of the first occurrence from within the list.
I'm having trouble trying to get the rest of the indexes that the item are stored.
Here is the code I have got so far to print the first index of search
:
if (names.contains(search)) {
System.out.println("name found!");
System.out.println(names.indexOf(search));
}
I understand that a loop needs to be added. But I am having trouble trying to formulate it.
Example
ArrayList<String> names = new ArrayList<String>();
names.add("Bob");
names.add("Jerry");
names.add("Bob");
names.add("Mick");
Say search = "Bob"
. My expected result would be {0,2}
. Instead, I am only able to get the index of the first occurrence (0
).
assert allIndexesOf(names, "Bob").equals(List.of(0, 2));
[...]
private List<Integer> allIndexesOf(List<?> list, Object o) {
// How can this be implemented?
}
How can I get all indexes that match the search string?