Java 8根据多个条件和日期对对象的Arraylist排序

问题描述

我有一个对象关系列表,里面有一个名为Contact的对象,它将包含elecType对象或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 )

我需要根据以下条件对Relationships,Contacts对象进行排序 如果代码是2,我需要从每个具有不同代码的联系人中获取最新日期的Relationship对象 即:将是以上示例的最终输出

Relationship:
  date:12/10/20
  Contact :
    code : 1
    postType(object) : (detail :xxx )
  Relationship:
  date:13/10/20
  Contact :
    code : 2
    postType(object) : (detail :zzz )

类似地,如果代码为1,我需要从每个具有不同的useCode,ecode的联系人记录中获取最新日期的关系

ie:根据以上数据,输出

    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 )

java类

    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
}

在Java 8或更高版本中实现此效果的最佳方法是什么(可以使用lambda和流实现)

解决方法

您只需在类Relationship中实现Comparable并使用以下方式对列表进行排序

Collections.sort(testList);

如果要过滤列表,则可以使用带有过滤器的流。

// filters a List with relationships with code 1
relationships.stream().filter(r -> r.getContacts().getCode() == 1).collect(Collectors.asList());