Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arraylist

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.

like image 748
Girish Setti Avatar asked Feb 04 '19 06:02

Girish Setti


People also ask

How to find the index of given element of a Java list?

How to find the index of given element of a Java List? How to find the index of given element of a Java List? The indexOf (Object) method of the java.util.ArrayList class returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

What is indexOf in Java list interface?

Java List indexOf () Method The indexOf () method of List interface returns the index of the first occurrence of the specified element in this list. It returns -1 if the specified element is not present in this list.

What is ArrayList get (index) method in Java?

ArrayList get(index) method in Java with examples. The get() method of ArrayList in Java is used to get the element of a specified index within the list. Syntax : Parameter : index:index of the elements to be returned. It is of data-type int. Returns : It returns the element at the specified index in the given list.

What is the use of indexOf(object O) in Java?

If the given value is present multiple times in the list then it takes the first occurrence of the value and returns its index. indexOf (Object o) method takes Object type argument. So that means any value or object can be passed to this method. And also a null value can be passed. All these are legal to do but it throws runtime exceptions.


3 Answers

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);
like image 64
michal.jakubeczy Avatar answered Sep 28 '22 07:09

michal.jakubeczy


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 your 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
like image 43
oleg.cherednik Avatar answered Sep 28 '22 07:09

oleg.cherednik


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;
    }
  }
}
like image 29
Huldula Avatar answered Sep 28 '22 07:09

Huldula