Find out first and last occurrence of elements in ArrayList

In the previous post, we have seen how to find the sublist in a arrayList. In this post, we will see how to find out first and last occurrence of elements in ArrayList.

Let’s understand them one by one with example.

Find out last occurrence of element in arrayList:

We use the method names as lastIndexOf(Object obj) to find out last occurrence of element in arrayList. It returns the index value of last occurrence of element and if element is not present it returns -1.

Syntax:

public int lastIndexOf(Object obj)

Note: Index starts from zero(0).

Example:

import java.util.ArrayList;

public class ArrayListEx {

	public static void main(String[] args) {
		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("Orange");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Grapes");
		fruits.add("Banana");
		fruits.add("Apple");
		fruits.add("Orange");
		fruits.add("Orange");
		System.out.println("Total fruits: "+fruits.size());

		System.out.println("Last occurrence of Apple : "+fruits.lastIndexOf("Apple"));
		
		System.out.println("Last occurrence of Orange : "+fruits.lastIndexOf("Orange"));
		
		System.out.println("Last occurrence of Papaya : "+fruits.lastIndexOf("Papaya"));   //Not present , returns -1
	}
}

Output:

Total fruits: 8
Last occurrence of Apple : 5
Last occurrence of Orange : 7
Last occurrence of Papaya : -1


Find out first occurrence of element in arrayList:

We use the method names as IndexOf(Object obj) to find out first occurrence of element in  arrayList. It returns the index value of first occurrence of element and if element is not present it returns -1.

Syntax:

public int IndexOf(Object obj)

Note: Index starts from zero(0).

Example:

import java.util.ArrayList;

public class ArrayListEx {

	public static void main(String[] args) {
		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("Orange");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Grapes");
		fruits.add("Banana");
		fruits.add("Apple");
		fruits.add("Orange");
		fruits.add("Orange");
		System.out.println("Total fruits: "+fruits.size());

		System.out.println("First occurrence of Apple : "+fruits.indexOf("Apple"));
		
		System.out.println("First occurrence of Orange : "+fruits.indexOf("Orange"));
		
		System.out.println("First occurrence of Papaya : "+fruits.indexOf("Papaya"));//Not present,returns -1
	}
}

Output:

Total fruits: 8
First occurrence of Apple : 2
First occurrence of Orange : 0
First occurrence of Papaya : -1


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...