如何在 Java 中搜索列表?
流可用于在列表中搜索项目。
Student student2 = list.stream().filter(s -> {return s.getRollNo() == rollNo);}).findAny().orElse(null);
在此示例中,我们按学号搜索学生。
示例
以下是展示如何使用流在列表中搜索项目的示例 −
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 + "]"; } }
输出
将产生以下结果 −
List: [[1,Zara], [2,Mahnaz], [3,Ayan]] [3,Ayan] null
广告