Ahmad R. Nazemi
Ahmad R. Nazemi

Reputation: 805

How to get index of List Object

Is there a way to retrieve the index of an object from a list by invoking a method on the list? For example, something like this:

class A{
    String a="";
    String b="";
}

List<A> alist= new ArrayList();

for (A a : alist) {
    a.getIndexInList();
}

Upvotes: 0

Views: 1176

Answers (2)

Batman
Batman

Reputation: 702

Why not use indexOf? If I recall correctly it is a built-in function of list.

 List<A> alist= new ArrayList<>();
 for (A a : alist) {
     int index = alist.indexOf(a);
 }

Only the list can give you the index. Unless the object in the array knows it's in an array it can't give you it's index.

Upvotes: 3

Andronicus
Andronicus

Reputation: 26066

There is no builtin solution, you can use external counter:

List<A> alist= new ArrayList();
int counter = 0;
for (A a : alist) {
    // logic
    counter++;
}

You could also create a map with indices as keys, something like:

IntStream.range(0, alist.size()).mapToObj(Integer::valueOf)
    .collect(Collectors.toMap(
            Function.identity(),
            alist::get
    ));

but alist needs to be effectively final.

Upvotes: 2

Related Questions