Everything you need to know about finding index of item in list with java
In this article, we will discuss finding the index of the list. List<T> is
an interface in java that provides many helpful methods for operating items of
lists. The IndexOf() method returns the index of an item if the item found
else it return -1.
Output:
Output:
There are two methods we can use for finding index:
- indexOf(Object obj):- This method returns the first index of an item if it is present in the list.
import java.util.Arrays; import java.util.List; public class FindIndex { public static void main(String[] args) { List<String> list = Arrays.asList( "Are", "you", "programmer","?", "you", "are", "awesome!." ); String findMe = "you"; System.out.println("Index of "+ findMe +": " +list.lastIndexOf(findMe)); } }
Output:
- lastIndexOf(Object obj):- This method returns the first index from the of an item if it is present in the list.
import java.util.Arrays; import java.util.List; public class FindIndex { public static void main(String[] args) { List<String> list = Arrays.asList( "Are", "you", "programmer","?", "you", "are", "awesome!." ); String findMe = "you"; System.out.println("Last Index of "+ findMe +": " +list.lastIndexOf(findMe)); } }
Output:
Comments
Post a Comment