Languages
[Edit]
EN

Java - get index of ArrayList element

0 points
Created by:
Broncono
316

In this article, we would like to show you how to get index of ArrayList element in Java.

Quick solution:

List<String> myArrayList = new ArrayList<>();

myArrayList.indexOf("value");


Practical example

In this example, we want to get the index of an item with Banana value from fruits ArrayList.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Grapes");

        int index = fruits.indexOf("Banana");

        System.out.println(index);
    }
}

Output:

1

Note:

If there are multiple items with specified value, the indexOf() method will return index of the first one. 

Java Collections - ArrayList

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join