How to Search Arraylist Element in Java


The example aims to search an element of ArrayList by binarySearch method in Java.

2 .Codes

package com.beginner.examples;

import java.util.ArrayList;
import java.util.Collections;

public class BinarySearchArrayListExample {

	public static void main(String[] args) {

		ArrayList weekList = new ArrayList();

		weekList.add("Sunday");
		weekList.add("Monday");
		weekList.add("Tuesday");
		weekList.add("Wednesday");
		weekList.add("Thursday");
		weekList.add("Friday");
		weekList.add("Saturday");

		//Use the Collections tools class, binarySearch(), to find the Collections
		int index = Collections.binarySearch(weekList, "Wednesday");
		
		System.out.println("Wednesday---->"+index);
	}

}

Output:

Wednesday---->3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments