Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I search a list in Java?
Java Streams (Java 8+) can be used to search for an item within a list by filtering elements based on a condition. The filter() method applies the search criteria, and findAny() returns the first matching element or null if no match is found.
Syntax
Student result = list.stream()
.filter(s -> s.getRollNo() == rollNo)
.findAny()
.orElse(null);
This filters the list for a student with the matching roll number. findAny() returns an Optional, and orElse(null) returns null if no match is found.
Example
The following example searches for students by roll number in a list ?
import java.util.ArrayList;
import java.util.List;
class Student {
private int rollNo;
private String name;
public Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
public int getRollNo() { return rollNo; }
public String getName() { return name; }
@Override
public String toString() {
return "[" + this.rollNo + "," + this.name + "]";
}
}
public class CollectionsDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(1, "Zara"));
list.add(new Student(2, "Mahnaz"));
list.add(new Student(3, "Ayan"));
System.out.println("List: " + list);
// Search for roll number 3 (exists)
final int rollNo1 = 3;
Student found = list.stream()
.filter(s -> s.getRollNo() == rollNo1)
.findAny()
.orElse(null);
System.out.println("Search rollNo 3: " + found);
// Search for roll number 4 (does not exist)
final int rollNo2 = 4;
Student notFound = list.stream()
.filter(s -> s.getRollNo() == rollNo2)
.findAny()
.orElse(null);
System.out.println("Search rollNo 4: " + notFound);
}
}
The output of the above code is ?
List: [[1,Zara], [2,Mahnaz], [3,Ayan]] Search rollNo 3: [3,Ayan] Search rollNo 4: null
Roll number 3 returns the matching Student object, while roll number 4 returns null since no match exists in the list.
Conclusion
Use stream().filter().findAny().orElse(null) to search for an item in a Java list by any criteria. For finding all matches instead of just the first one, replace findAny() with collect(Collectors.toList()) to get a list of all matching elements.
