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?
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.
An element in an ArrayList can be searched using the method java. util. ArrayList. indexOf().
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With