반응형
How to find index position of an element in a list when contains returns true
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?
What's wrong with:
benefit.indexOf(map4)
? It either returns an index or -1 if the items is not found.
BTW I strongly recommend wrapping the map in some object and use generics if possible.
Here is an example:
List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2
Use List.indexOf()
. This will give you the first match when there are multiple duplicates.
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.
반응형
'Nice programing' 카테고리의 다른 글
Why does Java let you cast to a collection? (0) | 2020.11.16 |
---|---|
C# Convert a Base64 -> byte[] (0) | 2020.11.16 |
Matplotlib에서 3D 큐브, 구 및 벡터 플로팅 (0) | 2020.11.16 |
Pass data through segue (0) | 2020.11.16 |
BREW 오류 : 심볼릭 링크 불가, 경로 쓰기 불가 (0) | 2020.11.16 |