Java 9 ArrayList and List index example
With ArrayList and List you can get the index of element, the first occurrence of several elements or the last one by:
- indexOf("A1")
- lastIndexOf("A2")
- indexOf and set - to find all indexes of repeated elements in ArrayList.
Example List get item index by value
In this example index of unique element is get, first and last occurrence of element which is repeated many times. In case of non existing element then -1 is returned:
import java.util.Arrays;
import java.util.List;
public class ArrayListIndex {
public static void main(String[] args) {
List<String> list = Arrays.asList("A1", "A2", "A3", "A2", "A2", "A3", "A7");
int index = list.indexOf("A1");
int lastOfMany = list.lastIndexOf("A2");
int firstOfMany = list.indexOf("A2");
int notFound = list.indexOf("A8");
System.out.println(index);
System.out.println(lastOfMany);
System.out.println(firstOfMany);
System.out.println(notFound);
}
}
result:
0
4
1
-1
ArrayList get indexes of repeated elements
Here is a small snippet showing how you can get indexes of all repeated elements in ArrayList or List:
import java.util.Arrays;
import java.util.List;
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("A1");
arrayList.add("A2");
arrayList.add("A3");
arrayList.add("A4");
arrayList.add("A3");
arrayList.add("A3");
arrayList.add("A5");
ArrayList<String> tempList = new ArrayList<>(arrayList);
for (int i = 0; i < tempList.size(); i++) {
int ind = tempList.indexOf("A3");
if(ind > 0) {
tempList.set(ind, "X");
System.out.println("A3 : " + ind);
}
}
for (String value : tempList) {
System.out.print(value + ", ");
}
result:
A3 : 2
A3 : 4
A3 : 5
A1, A2, X, A4, X, X, A5,