[Q#8192665][A#8192887] How to search for a string in an arraylist
https://stackoverflow.com/q/8192665
I want to search for a string in an arraylist. My ArrayList contains: Now I want to search for "bea" and it should return a list containing "bear" and "beat". How can I implement it?
Answer
https://stackoverflow.com/a/8192887
APIzation
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);
package com.stackoverflow.api;
import java.util.ArrayList;
import java.util.List;
public class Human8192887 {
public static List<String> search(List<String> list, String term) {
List<String> listClone = new ArrayList<>();
for (String string : list) {
if (string.matches("(?i)(" + term + ").*")) {
listClone.add(string);
}
}
System.out.println(listClone);
return listClone;
}
}
package com.stackoverflow.api;
import java.util.ArrayList;
import java.util.List;
/**
* How to search for a string in an arraylist
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/8192887">https://stackoverflow.com/a/8192887</a>
*/
public class APIzator8192887 {
public static List<String> search(List<String> list) throws Exception {
List<String> listClone = new ArrayList<String>();
for (String string : list) {
if (string.matches("(?i)(bea).*")) {
listClone.add(string);
}
}
return listClone;
}
}