

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I find an element in Java List?
There are couple of ways to find elements in a Java List.
Use indexOf() method.
Use contains() method.
Loop through the elements of a list and check if element is the required one or not.
Loop through the elements of a list using stream and filter out the element.
Example
Following is the example showing various methods to find an element −
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 + "]"; } }
Output
This will produce the following result −
List: [[1,Zara], [2,Mahnaz], [3,Ayan]] Ayan is present. [3,Ayan]
- Related Questions & Answers
- How do I add an element to an array list in Java?
- How do I find the size of a Java list?
- How do I turn a list into an array in Java?
- How do you add an element to a list in Java?
- How to find an element in a List with Java?
- How do I empty a list in Java?
- How do I search a list in Java?
- How do I find an element that contains specific text in Selenium Webdriver?
- How do I find an element that contains specific text in Selenium WebDriver (Python)?
- How do I insert elements in a Java list?
- How do you copy an element from one list to another in Java?
- How do I insert an item between two items in a list in Java?
- How do you check if an element is present in a list in Java?
- How do you get the index of an element in a list in Java?
- How do I check if an element is hidden in jQuery?
Advertisements