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:

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:

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
Print Friendly, PDF & Email
Find SubList of ArrayList
Compare two arrayLists in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *