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?
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.
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.
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.
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With