Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for a string in an arraylist

I want to search for a string in an arraylist. My ArrayList contains:

ArrayList <String> list = new ArrayList();  list.add("behold"); list.add("bend"); list.add("bet"); list.add("bear"); list.add("beat"); list.add("become"); list.add("begin"); 

Now I want to search for "bea" and it should return a list containing "bear" and "beat". How can I implement it?

like image 471
Romi Avatar asked Nov 19 '11 07:11

Romi


People also ask

How do you find a specific string in an ArrayList?

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). Get the array list. Using the for-each loop get each element of the ArrayList object.

How do you search for something in an ArrayList?

An element in an ArrayList can be searched using the method java. util. ArrayList. indexOf().

How do you check if a string is in an ArrayList Java?

ArrayList. contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.

How do you check if a string is present in a list of strings in Java?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.


1 Answers

 List <String> list = new ArrayList();              list.add("behold");             list.add("bend");             list.add("bet");             list.add("bear");             list.add("beat");             list.add("become");             list.add("begin");             List <String> listClone = new ArrayList<String>();             for (String string : list) {                if(string.matches("(?i)(bea).*")){                    listClone.add(string);                }            }         System.out.println(listClone); 
like image 196
Abhishek Avatar answered Sep 20 '22 06:09

Abhishek