java – ArrayList how to find the index of an element if the value is known?

Question:

Is it possible in to know the index of an element in an ArrayList if the value is known?

When you click on a list item, it shows the values

@Override
public int getItemCount() {
    return mFilteredCheeses.size();
}

public void filter(String query) {
    mFilteredCheeses = new ArrayList<>();
    for (String cheese : mDefaultCheeses) {
        if(cheese.toLowerCase().contains(query.toLowerCase())) {
            mFilteredCheeses.add(cheese);
        }
    }
    notifyDataSetChanged();
}

Is it possible to find out the index of an element, for example with the value Макс ?

Answer:

ArrayList has an indexOf method – it just looks for a suitable element and displays its index.

ArrayList<Object> test = new ArrayList<>();
test.add("yo");
test.add("yo2");
System.out.println(test.indexOf("yo2")); // Выведет: 1

If there are several identical values ​​in the list, then it will display the index of the first one found.

Scroll to Top