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...

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete