Reputation: 121
I have a list of object Relationships and inside that there is a object named Contact it will contain either elecType object or postType
**Relationships:**
Relationship:
date :15/10/20
Contact :
code : 1
usageCode : 1
elecType(object) :(ecode : 1, detail : ssss )
Relationship:
date :14/10/20
Contact :
code : 1
usageCode : 2
elecType(object) :(ecode : 2, detail :yyy )
Relationship:
date :10/10/20
Contact :
code : 1
usageCode : 2
elecType(object) :(ecode : 2, detail :eee )
Relationship:
date :13/10/20
Contact :
code : 1
usageCode : 2
elecType(object) :(ecode : 1, detail :zzz )
Relationship:
date :15/10/20
Contact :
code : 1
usageCode : 1
elecType(object) :(ecode : 2, detail :ttt )
Relationship:
date:12/10/20
Contact :
code : 1
postType(object) : ( detail :xxx )
Relationship:
date:11/10/20
Contact :
code : 2
postType(object) : (detail :yyy )
Relationship:
date:13/10/20
Contact :
code : 2
postType(object) : (detail :zzz )
i need to sort the Relationship,Contacts objects based on the below conditions if the code is 2, i need to get the latest dated Relationship objects from each Contacts which having different code ie : The will be final output from the above example
Relationship:
date:12/10/20
Contact :
code : 1
postType(object) : (detail :xxx )
Relationship:
date:13/10/20
Contact :
code : 2
postType(object) : (detail :zzz )
Similarly if the code is 1 , i need to get the latest dated Relationship from each Contacts records which having different usageCode,ecode
ie : from the above data,the output will be
Relationship:
date :15/10/20
Contact :
code : 1
usageCode : 1
elecType(object) :(ecode : 1, detail : ssss )
Relationship:
date :15/10/20
Contact :
code : 1
usageCode : 1
elecType(object) :(ecode : 2, detail :ttt )
Relationship:
date :13/10/20
Contact :
code : 1
usageCode : 2
elecType(object) :(ecode : 1, detail :zzz )
Relationship:
date :14/10/20
Contact :
code : 1
usageCode : 2
elecType(object) :(ecode : 2, detail :yyy )
public class Relationship {
private Date date;
private Contact contact;
}
public class Contact{
private Integer code;
private Integer usageCode;
private PostalType postalType;
private ElecType elecType;
}
public class PostalType{
private String detail;
}
public class ElecType{
private String detail;
private Integer eCode
}
What is the best way to implement this in Java 8 or higher (is it possible to achieve using lambda and streams)
Upvotes: 0
Views: 161
Reputation: 2767
You can just implement Comparable in your class Relationship and sort a list with
Collections.sort(testList);
If you want to filter your list, you can use a stream with filter.
// filters a List with relationships with code 1
relationships.stream().filter(r -> r.getContacts().getCode() == 1).collect(Collectors.asList());
Upvotes: 1