Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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? 
like image 604
Anthony Avatar asked Jan 25 '12 18:01

Anthony


People also ask

How do you find the position of an item in a list in Python?

To facilitate this, Python has an inbuilt function called index(). This function takes in the element as an argument and returns the index. By using this function we are able to find the index of an element in a list in Python.

How do you find the index of an object in a list?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error. To fix this issue, you need to use the in operator.

How do you find the index of an item in a list in Java?

indexOf() in Java. The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax : public int IndexOf(Object o) obj : The element to search for.

How do you find the index of an element in an ArrayList?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().


1 Answers

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.

like image 86
Tomasz Nurkiewicz Avatar answered Oct 15 '22 22:10

Tomasz Nurkiewicz