Home  >  Forum  >  Core Java
Post New Query

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


joined on
May 01,2016
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?
 

joined on
March 14,2013
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




Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us