简体   繁体   English

当包含返回true时如何在列表中查找元素的索引位置

[英]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 .我有一个HashMap List ,所以我使用List.contains来确定列表是否包含指定的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?
benefit.indexOf(map4)

It either returns an index or -1 if the items is not found.如果未找到项目,它要么返回索引,要么返回 -1。

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() .使用List.indexOf() This will give you the first match when there are multiple duplicates.当有多个重复项时,这将为您提供第一个匹配项。

int indexOf(Object o)此方法返回此列表中第一次出现指定元素的索引,如果此列表不包含此元素,则返回 -1。

int indexOf() can be used.可以使用int indexOf() It returns -1 if no matching finds如果找不到匹配项,则返回 -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM