How do I search a list in Java?



Streams can be used to search an item within list.

Student student2 = list.stream().filter(s -> {return s.getRollNo() == rollNo);}).findAny().orElse(null);

In this example, we're searching a student by roll number.

Example

Following is the example showing the usage of streams to search an item in a list −

package com.tutorialspoint; import java.util.ArrayList; import java.util.List; 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);       final int rollNoToSearch = 3;       Student student = list.stream().filter(s -> {return s.getRollNo() == rollNoToSearch;}).findAny().orElse(null);       System.out.println(student);       final int rollNoToSearch1 = 4;       student = list.stream().filter(s -> {return s.getRollNo() == rollNoToSearch1;}).findAny().orElse(null);       System.out.println(student);    } } 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 void setRollNo(int rollNo) {       this.rollNo = rollNo;    }    public String getName() {       return name;    }    public void setName(String name) {       this.name = name;    }    @Override    public boolean equals(Object obj) {       if(!(obj instanceof Student)) {          return false;       }       Student student = (Student)obj;       return this.rollNo == student.getRollNo() && this.name.equals(student.getName());    }    @Override    public String toString() {       return "[" + this.rollNo + "," + this.name + "]";    } }

Output

This will produce the following result −

List: [[1,Zara], [2,Mahnaz], [3,Ayan]] [3,Ayan] null
Updated on: 2022-05-09T13:54:32+05:30

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements