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

Comments

Popular posts from this blog

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

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

Java - DES Encryption and Decryption example

Java - Blowfish Encryption and decryption Example

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

ReactJS - Bootstrap - Buttons

Top 5 Java ORM tools - 2024

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java - How to Count the Number of Occurrences of Substring in a String