Java 如何在List中查找元素

Java 如何在List中查找元素

有几种方法可以在Java List中查找元素。

  • 使用indexOf()方法。

  • 使用contains()方法。

  • 通过循环遍历列表的元素,检查元素是否为所需的元素。

  • 使用流循环遍历列表的元素,并过滤出所需的元素。

示例

以下示例展示了查找元素的多种方法:

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);
      Student student = new Student(3, "Ayan");
      for (Student student1 : list) {
         if(student1.getId() == 3 && student.getName().equals("Ayan")) {
            System.out.println("Ayan is present.");
         }
      }
      Student student2 = list.stream().filter(s -> {return       s.equals(student);}).findAny().orElse(null);
      System.out.println(student2);
   }
}
class Student {
   private int id;
   private String name;
   public Student(int id, String name) {
      this.id = id;
      this.name = name;
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   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.id == student.getId() && this.name.equals(student.getName());
   }
   @Override
   public String toString() {
      return "[" + this.id + "," + this.name + "]";
   }
}

输出

这将产生以下结果:

List: [[1,Zara], [2,Mahnaz], [3,Ayan]]
Ayan is present.
[3,Ayan]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程