In Java 8 and later, you can use the findFirst method of the Stream interface to find the first element in a List that matches a given condition.
To find an element in a List by a specific property, you can use the findFirst method in combination with the filter method, which allows you to specify a predicate (a condition) that the elements of the List must satisfy.
Here is an example of how you can use the findFirst and filter methods to find an element in a List by a specific property:
import java.util.List;
import java.util.Arrays;
public class MyClass {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
);
Person result = people.stream()
.filter(p -> "Charlie".equals(p.getName()))
.findFirst()
.orElse(null);
System.out.println(result); // Outputs "Person{name='Charlie', age=35}"
}
}
class Person {
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
}