EN
Java - get index of ArrayList element
0 points
In this article, we would like to show you how to get index of ArrayList element in Java.
Quick solution:
xxxxxxxxxx
1
List<String> myArrayList = new ArrayList<>();
2
3
myArrayList.indexOf("value");
In this example, we want to get the index of an item with Banana
value from fruits
ArrayList.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<String> fruits = new ArrayList<>();
7
8
fruits.add("Apple");
9
fruits.add("Banana");
10
fruits.add("Cherry");
11
fruits.add("Grapes");
12
13
int index = fruits.indexOf("Banana");
14
15
System.out.println(index);
16
}
17
}
Output:
xxxxxxxxxx
1
1
Note:
If there are multiple items with specified value, the
indexOf()
method will return index of the first one.