Java8 使用 lambda 对 List、Set 进行排序

 

数据结构

public class InsurerClientDto {

    private Long insurerClientId;
    private String clientOidType;
    private Long clientOid;
    private String clientCode;
    private String clientDesc;
    private Long hqHdrId;

    public InsurerClientDto() {
        //Default constructor
    }

    public void setInsurerClientId(Long insurerClientId) {
        this.insurerClientId = insurerClientId;
    }

    public Long getInsurerClientId() {
        return insurerClientId;
    }

    public void setClientOidType(String clientOidType) {
        this.clientOidType = clientOidType;
    }

    public String getClientOidType() {
        return clientOidType;
    }

    public void setClientOid(Long clientOid) {
        this.clientOid = clientOid;
    }

    public Long getClientOid() {
        return clientOid;
    }

    public String getClientCode() {
        return clientCode;
    }

    public void setClientCode(String clientCode) {
        this.clientCode = clientCode;
    }

    public void setClientDesc(String clientDesc) {
        this.clientDesc = clientDesc;
    }

    public String getClientDesc() {
        return clientDesc;
    }

    public Long getHqHdrId() { return hqHdrId; }

    public void setHqHdrId(Long hqHdrId) { this.hqHdrId = hqHdrId; }

    @Override
    public String toString() {
        return "InsurerClientDto [insurerClientId=" + insurerClientId + ", clientOidType=" + clientOidType
                + ", clientOid=" + clientOid + ", clientCode=" + clientCode + ", clientDesc=" + clientDesc
                + ", hqHdrId=" + hqHdrId + "]";
    }
}

 

 

 

数据准备

List<InsurerClientDto> insurerClientDto = new ArrayList<>();
InsurerClientDto dto
= new InsurerClientDto(); dto.setClientCode("KP03S"); insurerClientDto.add(dto);
dto
= new InsurerClientDto(); dto.setClientCode("KP048"); insurerClientDto.add(dto);
dto
= new InsurerClientDto(); dto.setClientCode("KP003"); insurerClientDto.add(dto);

 

 

3种方法

1、不能实现排序

Comparator<InsurerClientDto> clinentComparator = (v1, v2) -> v1.getClientCode().compareTo(v2.getClientCode());
insurerClientDto.stream().sorted(clinentComparator.reversed());

不能实现排序原因:

 

 

2、可以实现排序

Comparator<InsurerClientDto> clinentComparator = Comparator.comparing(InsurerClientDto :: getClientCode, String.CASE_INSENSITIVE_ORDER);
insurerClientDto.sort(clinentComparator);

 

 

 

3、可以实现排序

insurerClientDto.sort((d1, d2) -> d1.getClientCode().compareTo(d2.getClientCode()));
//或(用法相同,上面省略类名而已)
insurerClientDto.sort((InsurerClientDto d1, InsurerClientDto d2) -> d1.getClientCode().compareTo(d2.getClientCode()));

 

原文链接:

https://www.cnblogs.com/poterliu/p/13231500.html

 

 

参考链接:

https://developer.aliyun.com/article/714142

https://my.oschina.net/HJCui/blog/1573344

 

posted @ 2020-07-03 17:15  poterliu  阅读(3194)  评论(0编辑  收藏  举报