How to find an object in a List by property using Java 8




Asked on May 01, 2016
I have a class 
public class Person {
private int pid;
private String location;
private String name;
}
I have overridden hashCode() and equals() methods.
Now I have a List<Person>. 

How to find an object in our list by property(suppose pid) using Java 8?
 




Replied on May 01, 2016
Create a Predicate and use Java 8 Filter.

Person getPersonById(int pid) {
Predicate<Person> personPredicate = p-> p.getPid() == pid;
Person obj = list.stream().filter(personPredicate).findFirst().get();
return obj;
}

It will return Person object with given pid fetching from List.


Write Answer










©2024 concretepage.com | Privacy Policy | Contact Us