List is an ordered collection implementation under Java's Collections Framework, where each elemant is assigned a zero-based integer position corresponding to its placement in the sequence. To fetch the position of a specific element by value, you can use either built-in List methods or implement custom lookup logic depending on use case requirements.
Built-in indexOf() Method
The List interface provides a native indexOf() method that accepts a target object as input and returns the index of the first occurrence of the matching element in the sequence. If no matching element is found, the method returns -1.
import java.util.ArrayList;
import java.util.List;
public class ListIndexDemo {
public static void main(String[] args) {
List<Double> scoreRecords = new ArrayList<>();
scoreRecords.add(76.5);
scoreRecords.add(91.0);
scoreRecords.add(82.3);
int targetPosition = scoreRecords.indexOf(91.0);
System.out.println("Position of score 91.0: " + targetPosition);
}
}
When executed, the above code outputs Position of score 91.0: 1, as elements are zero-indexed.
Custom Index Lookup Implementation
For use cases that require custom matching logic (such as case-insensitive string matching or null-safe lookups), you can implement a generic lookup functon to traverse the list and return the matching element's index.
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class CustomIndexLookup {
public static <T> int findElementPosition(List<T> inputList, T targetElement) {
for (int pos = 0; pos < inputList.size(); pos++) {
if (Objects.equals(inputList.get(pos), targetElement)) {
return pos;
}
}
return -1;
}
public static void main(String[] args) {
List<String> fruitInventory = new ArrayList<>();
fruitInventory.add("Orange");
fruitInventory.add("Mango");
fruitInventory.add("Grape");
int mangoPosition = findElementPosition(fruitInventory, "Mango");
System.out.println("Position of Mango in inventory: " + mangoPosition);
}
}
The Objects.equals() call in the above implementation ensures null safety, avoiding NullPointerExceptions when either the target element or list elements are null. The function returns -1 for non-existent elements, matching the behavior of the built-in indexOf() method.