如何通过Java列表中的属性获取对象的索引

我想通过Java中的属性获取列表中对象的索引。

例子:


List<MyObj> list = new ArrayList<>();

list.add(new MyObj("Ram");

list.add(new MyObj("Girish");

list.add(new MyObj("Ajith");

list.add(new MyObj("Sai");  


public class MyObj {

public String name;

    public MyObj(String name){

        this.name=name;

    }

}

现在,我想获取包含名称为“Girish”的对象的索引。请让我知道 JAVA 中的代码。


慕仙森
浏览 553回答 3
3回答

呼唤远方

如果您想要一个带有流的解决方案,请使用这个:int&nbsp;index&nbsp;=&nbsp;IntStream.range(0,&nbsp;list.size()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(i&nbsp;->&nbsp;list.get(i).name.equals(searchName)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.findFirst() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.orElse(-1);

慕莱坞森

如果您有List,您所能做的就是遍历每个元素并检查所需的属性。这是O(n)。public static int getIndexOf(List<MyObj> list, String name) {&nbsp; &nbsp; int pos = 0;&nbsp; &nbsp; for(MyObj myObj : list) {&nbsp; &nbsp; &nbsp; &nbsp; if(name.equalsIgnoreCase(myObj.name))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return pos;&nbsp; &nbsp; &nbsp; &nbsp; pos++;&nbsp; &nbsp; }&nbsp; &nbsp; return -1;}如果您想提高性能。然后你可以实现你自己的数据结构。请注意,关键特性是您的 key 属性应该是 a 的 key,HashMap而 valueHashMap应该是 index。然后你会得到O(1)的性能。public static final class IndexList<E> extends AbstractList<E> {&nbsp; &nbsp; private final Map<Integer, E> indexObj = new HashMap<>();&nbsp; &nbsp; private final Map<String, Integer> keyIndex = new HashMap<>();&nbsp; &nbsp; private final Function<E, String> getKey;&nbsp; &nbsp; public IndexList(Function<E, String> getKey) {&nbsp; &nbsp; &nbsp; &nbsp; this.getKey = getKey;&nbsp; &nbsp; }&nbsp; &nbsp; public int getIndexByKey(String key) {&nbsp; &nbsp; &nbsp; &nbsp; return keyIndex.get(key);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public int size() {&nbsp; &nbsp; &nbsp; &nbsp; return keyIndex.size();&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public boolean add(E e) {&nbsp; &nbsp; &nbsp; &nbsp; String key = getKey.apply(e);&nbsp; &nbsp; &nbsp; &nbsp; if (keyIndex.containsKey(key))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalArgumentException("Key '" + key + "' duplication");&nbsp; &nbsp; &nbsp; &nbsp; int index = size();&nbsp; &nbsp; &nbsp; &nbsp; keyIndex.put(key, index);&nbsp; &nbsp; &nbsp; &nbsp; indexObj.put(index, e);&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public E get(int index) {&nbsp; &nbsp; &nbsp; &nbsp; return indexObj.get(index);&nbsp; &nbsp; }}演示:IndexList<MyObj> list = new IndexList<>(myObj -> myObj.name);list.add(new MyObj("Ram"));list.add(new MyObj("Girish"));list.add(new MyObj("Ajith"));list.add(new MyObj("Sai"));System.out.println(list.getIndexByKey("Ajith"));&nbsp; &nbsp; // 2

翻翻过去那场雪

如果您更改 .equals 函数,indexOf() 将起作用我建议只是迭代int getIndex(String wanted){&nbsp; for(int i = 0; i<list.size(); i++){&nbsp; &nbsp; if(list.get(i).name.equals(wanted)){&nbsp; &nbsp; &nbsp; return i;&nbsp; &nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java