How to find index position of an element in a list when contains returns true

Java

Java Problem Overview


I've got a List of HashMap so I'm using List.contains to find out if the list contains a specified HashMap. In case it does, I want to fetch that element from the list, so How do I find out index position of where the element is?

    List benefit = new ArrayList();
    HashMap map = new HashMap();
    map.put("one", "1");
    benefit.add(map);
    HashMap map4 = new HashMap();
    map4.put("one", "1");

    System.out.println("size: " + benefit.size());
    System.out.println("does it contain orig: " + benefit.contains(map));
    System.out.println("does it contain new: " + benefit.contains(map4));
    
    if (benefit.contains(map4))
        //how to get index position where map4 was found in benefit list?

Java Solutions


Solution 1 - Java

benefit.indexOf(map4)

It either returns an index or -1 if the items is not found.

I strongly recommend wrapping the map in some object and use generics if possible.

Solution 2 - Java

Here is an example:

List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2

Solution 3 - Java

Solution 4 - Java

Use List.indexOf(). This will give you the first match when there are multiple duplicates.

Solution 5 - Java

Solution 6 - Java

int indexOf(Object o) This method returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element.

Solution 7 - Java

int indexOf() can be used. It returns -1 if no matching finds

Solution 8 - Java

Use benefit.indexOf(map4). This should simply return the index of the map or if it doesn't exist it returns -1.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthonyView Question on Stackoverflow
Solution 1 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - Javahamza raissiView Answer on Stackoverflow
Solution 3 - JavaBhesh GurungView Answer on Stackoverflow
Solution 4 - JavaOliver CharlesworthView Answer on Stackoverflow
Solution 5 - JavaAndrei LEDView Answer on Stackoverflow
Solution 6 - JavacyberscientistView Answer on Stackoverflow
Solution 7 - Javasarwadnya deshpandeView Answer on Stackoverflow
Solution 8 - JavaVijay KambalaView Answer on Stackoverflow