How to find the index position of an item in a list when it contains true

I have a List from HashMap , so I use List.contains to find out if the list contains the specified HashMap . In case this is the case, I want to extract this element from the list, so How do I know the position of the index, where is the element?

  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? 
+43
java
Jan 25 '12 at 18:57
source share
6 answers

What happened with:

 benefit.indexOf(map4) 

? It either returns an index, or -1 if no elements are found.

BTW I strongly recommend wrapping the card in an object and, if possible, using generics.

+83
Jan 25 '12 at 19:00
source share
+12
Jan 25 '12 at 19:00
source share

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

+5
Jan 25 '12 at 19:00
source share
+3
Jan 25 '12 at 19:00
source share

Here is an example:

 List<String> names; names.add("toto"); names.add("Lala"); names.add("papa"); int index = names.indexOf("papa"); // index = 2 
+3
Aug 05 '14 at 11:23
source share

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.

+1
Jan 25 '12 at 19:08
source share



All Articles