- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Java Program to Search an Element in a Circular Linked List
- How to search in a List of Java object?
- Python Program To Search An Element In A List
- How do I search a list in Java?
- How do you search for an element in an ArrayList in Java?
- How to search for an item in a Lua List?
- How to search for an element in JavaScript array?
- How to search for an array element in TypeScript?
- How to search for a pattern in a Java string?
- C++ Program to Search for an Element in a Binary Search Tree
- Python program to search an element in a Circular Linked List
- Python program to search an element in a doubly linked list
- Java Program for Search an element in a sorted and rotated array
- Search a particular element in a LinkedList in Java
- How to search for a string in an ArrayList in java?

Advertisements