根据其中的一个字段对Java集合对象进行排序


问题内容

我有以下收藏:

Collection<AgentSummaryDTO> agentDtoList = new ArrayList<AgentSummaryDTO>();

AgentSummaryDTO这个样子的:

public class AgentSummaryDTO implements Serializable {
    private Long id;
    private String agentName;
    private String agentCode;
    private String status;
    private Date createdDate;
    private Integer customerCount;
}

现在我必须agentDtoList根据customerCount字段对集合进行排序,如何实现呢?


问题答案:

这是我的“ 1班轮”:

Collections.sort(agentDtoList, new Comparator<AgentSummaryDTO>(){
   public int compare(AgentSummaryDTO o1, AgentSummaryDTO o2){
      return o1.getCustomerCount() - o2.getCustomerCount();
   }
});

Java 8的更新:对于int数据类型

 Collections.sort(agentDtoList, (o1, o2) -> o1.getCustomerCount() - o2.getCustomerCount());

甚至:

 Collections.sort(agentDtoList, Comparator.comparing(AgentSummaryDTO::getCustomerCount));

对于String数据类型(如注释中所示)

Collections.sort(list, (o1, o2) -> (o1.getAgentName().compareTo(o2.getAgentName())));

..它期望吸气剂 AgentSummaryDTO.getCustomerCount()