Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting index of an item in List of non primitive type

Tags:

java

list

Here is my class Info

public class Info {
    public String imei;
    public Integer delta;
}

and my

List<Info> Records;

Is there a simple way to get the index of an Info, where for example imei is 356307044597945, or I must go through the list, comparing all the elements?

like image 790
Carmine Avatar asked Feb 04 '26 05:02

Carmine


2 Answers

There is no method in List interface to find the objects on the basis of an object attribute. So you need to iterate through your List.

Better use Map to provide a key value pair mappings for your need. Map is definitely a better choice because using Map you will be able to get the desired object with O(1) complexity instead of O(n) when compared to iteration over List.

You may use imei as the key for your map and corresponding Info object as the value.

like image 175
Juned Ahsan Avatar answered Feb 05 '26 19:02

Juned Ahsan


You could implement the equals/hashCode methods:

public class Info {

    public String imei;
    public Integer delta;

    public Info(String imei) {
        this.imei = imei;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Info && obj.imei.equals(imei);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(new Object[] { imei });
    }

}

Then:

int index = records.indexOf(new Info("356307044597945"));

Not sure if it's a good practice though, waiting for up or down votes ;)

like image 39
sp00m Avatar answered Feb 05 '26 19:02

sp00m