w3resource

Java: Search an element in a array list


7. Search Element in ArrayList

Write a Java program to search for an element in an array list.

Pictorial Presentation:

Java Collection, ArrayList Exercises: Search an element in a list

Sample Solution:-

Java Code:

import java.util.*;
  public class Exercise7 {
  public static void main(String[] args) {
  // Creae a list and add some colors to the list
  List<String> list_Strings = new ArrayList<String>();
  list_Strings.add("Red");
  list_Strings.add("Green");
  list_Strings.add("Orange");
  list_Strings.add("White");
  list_Strings.add("Black");
  // Search the value Red
    if (list_Strings.contains("Red")) {
    System.out.println("Found the element");
    } else {
    System.out.println("There is no such element");
    }
 }
}

Sample Output:

Found the element

Flowchart:

Flowchart: Search an element in a list.

For more Practice: Solve these Related Problems:

  • Write a Java program to search for a specific string in an ArrayList using binary search after sorting the list.
  • Write a Java program to implement a case-insensitive search for an element in an ArrayList using streams.
  • Write a Java program to search for an element and return its index, or -1 if not found, using a custom loop.
  • Write a Java program to search for multiple occurrences of an element in an ArrayList and print all indices where it appears.

Go to:


PREV : Remove Third Element.
NEXT : Sort ArrayList.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.