How to get the index of object by its property in Java list

柔情痞子 提交于 2020-02-15 18:38:22

问题


I would like to get the index of an object in a list by its property in Java.
Example:

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;
    }
}

Now, I would like to the get the index of an Object which contains the name as "Girish". Please do let me know the code in JAVA.


回答1:


In case you have a List, all you can do is to iterate over each element and check required property. This is O(n).

public static int getIndexOf(List<MyObj> list, String name) {
    int pos = 0;

    for(MyObj myObj : list) {
        if(name.equalsIgnoreCase(myObj.name))
            return pos;
        pos++;
    }

    return -1;
}

In case you want to increase performance. Then you could implement you own data structure. Note, that key feature is that your key property should be a key of a HashMap and value of HashMap should be index. Then you get O(1) performance.

public static final class IndexList<E> extends AbstractList<E> {
    private final Map<Integer, E> indexObj = new HashMap<>();
    private final Map<String, Integer> keyIndex = new HashMap<>();
    private final Function<E, String> getKey;

    public IndexList(Function<E, String> getKey) {
        this.getKey = getKey;
    }

    public int getIndexByKey(String key) {
        return keyIndex.get(key);
    }

    @Override
    public int size() {
        return keyIndex.size();
    }

    @Override
    public boolean add(E e) {
        String key = getKey.apply(e);

        if (keyIndex.containsKey(key))
            throw new IllegalArgumentException("Key '" + key + "' duplication");

        int index = size();
        keyIndex.put(key, index);
        indexObj.put(index, e);
        return true;
    }

    @Override
    public E get(int index) {
        return indexObj.get(index);
    }
}

Demo:

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"));    // 2



回答2:


indexOf() will work if you change the .equals function

I'd suggest just iterating through

int getIndex(String wanted){
  for(int i = 0; i<list.size(); i++){
    if(list.get(i).name.equals(wanted)){
      return i;
    }
  }
}



回答3:


If you want a solution with stream use this one:

int index = IntStream.range(0, list.size())
     .filter(i -> list.get(i).name.equals(searchName))
     .findFirst();
     .orElse(-1);



回答4:


indexOf() will return the index of the first occurrence of a value. For example:

int myIndex = list.indexOf("Ram")

(Note though that your arraylist doesn't contain "Ram", it contains an object of type MyObj with a name of "Ram")

Bear in mind ArrayLists start at 0 not one.



来源:https://stackoverflow.com/questions/54511107/how-to-get-the-index-of-object-by-its-property-in-java-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!