To find an item in a list in Java by a specific property, you can use the stream()
method to create a stream of the list, and then use the filter()
method to filter the elements based on the property.
Here's an example of how to do it:
import java.util.Arrays; import java.util.List; import java.util.Optional; public class Main { public static class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } public static void main(String[] args) { List<Person> list = Arrays.asList( new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 35) ); // Find the person with the name "Bob" Optional<Person> person = list.stream() .filter(p -> p.getName().equals("Bob")) .findFirst(); if (person.isPresent()) { System.out.println(person.get().getAge()); // prints "30" } } }
This code creates a list of Person
objects and then uses the filter()
method to find the first person with the name "Bob". The findFirst()
method is used to get the first element of the stream, and the isPresent()
method is used to check if an element was found.
You can use a similar approach to find an item in a list by any property, as long as you use the appropriate stream and filter methods.
Note that this approach returns an Optional
object, which is a container that may or may not contain a value. This can be useful to avoid NullPointerExceptions
when the item is not found in the list.