How to search a String in a List in Java?
In this section, we will show you how to search a string in a List in Java. We can use .contains(), .startsWith() or .matches() to search for a string in ArrayList.
Java 8 Example
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("India");
list.add("USA");
list.add("Japan");
list.add("Brazil");
list.add("Israel");
//.contains example
List<String> result1 = list
.stream()
.filter(x -> x.contains("India"))
.collect(Collectors.toList());
System.out.println(result1);
//.startsWith example
List<String> result2 = list
.stream()
.filter(x -> x.startsWith("I"))
.collect(Collectors.toList());
System.out.println(result2);
//.matches example
List<String> result3 = list
.stream()
.filter(x -> x.matches("(?i)b.*"))
.collect(Collectors.toList());
System.out.println(result3);
}
}
Console Output:
[India]
[India, Israel]
[Brazil]
Old style
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("India");
list.add("USA");
list.add("Japan");
list.add("Brazil");
list.add("Israel");
List<String> result = new ArrayList<>();
for (String s : list) {
if (s.contains("India")) {
result.add(s);
}
//startsWith
if (s.startsWith("I")) {
result.add(s);
}
//regex
if (s.matches("(?i)j.*")) {
result.add(s);
}
}
System.out.println(result);
}
}
Console Output:
[India, India, Japan, Israel]
More...