如何使用 Java 在 List 中查找元素?

javaobject oriented programmingprogramming更新于 2025/2/4 17:48:17

List 接口扩展了 Collection 接口,表示存储元素序列的集合。列表用户可以非常精确地控制将元素插入 List 中的位置。这些元素可通过其索引访问,并且可以搜索。 ArrayList 是 Java 开发人员中最流行的 List 接口实现。

在 Java List 中,有几种查找元素的方法。

  • 使用 indexOf() 方法。 - 如果元素存在,则此方法返回元素的索引,否则返回 -1。

  • 使用 contains() 方法。 - 如果元素存在,则此方法返回 true,否则返回 false。

  • 循环遍历列表的元素并检查元素是否是必需的。

  • 使用流循环遍历列表的元素并过滤掉元素。

在本文中,我们将在示例中介绍上述每种方法。

示例 1

以下是显示使用 indexOf() 和 contains() 方法来查找的示例列表中的元素 −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("Zara");
      list.add("Mahnaz");
      list.add("Ayan");
     
      System.out.println("List: " + list);
      String student = "Ayan";
     
      if(list.indexOf(student) != -1) {
         System.out.println("Ayan is present.");
      }
      if(list.contains(student)) {
         System.out.println("Ayan is present.");
      }
   }
}

输出

这将产生以下结果 −

List: [Zara, Mahnaz, Ayan]
Ayan is present.
Ayan is present.

示例 2

以下示例展示了如何使用迭代和流在列表中查找元素 −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("Zara");
      list.add("Mahnaz");
      list.add("Ayan");
     
      System.out.println("List: " + list);
      String student = "Ayan";
     
      for (String student1 : list) {
         if(student1 == "Ayan") {
            System.out.println("Ayan is present.");
         }
      }
      String student2 = list.stream().filter(s -> {return s.equals(student);}).findAny().orElse(null);
      System.out.println(student2);
   }
}

输出

这将产生以下结果 −

List: [Zara, Mahnaz, Ayan]
Ayan is present.
Ayan

相关文章


有用资源