How to search for element in a List in Java?



Let us first create a String array:

String arr[] = { "One", "Two", "Three", "Four", "Five" };

Now convert the above array to List:

ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr));

Sort the collection:

Collections.sort(arrList);

Now, find the elements “Four” in the list. We will get the index at which the specified element is found:

int index = Collections.binarySearch(arrList, "Four");

Example

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Demo {
   public static void main(String args[]) {
      String arr[] = { "One", "Two", "Three", "Four", "Five" };
      ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr));
      Collections.sort(arrList);
      System.out.println(arrList);
      int index = Collections.binarySearch(arrList, "Four");
      System.out.println("The element exists at index = " + index);
   }
}

Output

[Five, Four, One, Three, Two]
The element exists at index = 1

Advertisements