How to search for a string in an ArrayList in java?


The contains a () method of the String class accepts Sting value as a parameter, verifies whether the current String object contains the specified string and returns true if it does (else false).

Therefore, to for a string in an ArrayList −

  • Get the array list.

  • Using the for-each loop get each element of the ArrayList object.

  • Verify whether each element in the array list contains the required string.

  • If so print the elements.

Example

 Live Demo

import java.util.ArrayList;
import java.util.Iterator;
public class FindingString{
   public static void main(String[] args){
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Java Script");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the array list: ");
      for (String element : list){
         if (element.contains("Java")){
               System.out.println(element);
         }
      }
   }
}

Output

Contents of the array list:
JavaFX
Java
Java Script
raja
Published on 15-Oct-2019 10:23:09
Advertisements