【问题标题】:Sort a Java collection object based on one field in it根据其中的一个字段对 Java 集合对象进行排序
【发布时间】:2012-09-14 13:32:31
【问题描述】:

我有以下收藏:

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;
}

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

【问题讨论】:

标签: java sorting collections


【解决方案1】:

您可以使用此代码

agentDtoList.sort((t1, t2) -> t1.getCustomerCount());

【讨论】:

    【解决方案2】:

    对于任何正在寻找答案的人:

    您还可以使用 JAVA-8 Stream-API 对列表进行排序。

    List<AgentSummaryDTO> sortedList = agentDtoList.stream()
      .sorted(Comparator.comparing(AgentSummaryDTO::getCustomerCount).reversed())
      .collect(Collectors.toList());
    

    【讨论】:

      【解决方案3】:

      Java 8 的更新。它有效:

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

      【讨论】:

        【解决方案4】:

        这是我的“1liner”:

        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));
        

        对于字符串数据类型(如注释)

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

        ..它需要 getter AgentSummaryDTO.getCustomerCount()

        【讨论】:

        • 我用 return agentSummary1.getCustomerCount().compareTo(agentSummary2.getCustomerCount());
        • 如果我需要使用 agentname 而不是 customercount 对相同的示例进行排序怎么办?我需要对字符串字段进行排序。请建议
        • @TanuGarg 而不是return o1.getCustomerCount() - o2.getCustomerCount();,你会得到o1.getAgentName().compareTo(o2.getAgentName())
        • 根据.compareTo的结果,如果比较的字符串相同,则返回0,如果第一个较大,则返回负值,否则返回正值。它对字符串使用字典顺序。然后这个结果被Java中的排序算法使用(恰好是合并排序)
        • @karthik_varma_k Collections.sort(agentDtoList, Comparator.comparing(AgentSummaryDTO::getCustomerCount).reversed());
        【解决方案5】:

        看看下面的代码。

        package test;
        
        import java.io.Serializable;
        import java.util.ArrayList;
        import java.util.Collections;
        import java.util.Date;
        import java.util.List;
        
        public class AgentSummary {
            private Long id;
            private String agentName;
            private String agentCode;
            private String status;
            private Date createdDate;
            private Integer customerCount;
        
            /**
             * @param args
             */
            public static void main(String[] args) {
                new AgentSummary().addObjects();   
            }
        
            public void addObjects(){
                List<AgentSummaryDTO> agentSummary = new ArrayList<AgentSummaryDTO>();
                for (int j = 0; j < 10; j++) {
                    agentSummary.add(new AgentSummaryDTO(j));
                }
                Collections.sort(agentSummary);
        
                for (AgentSummaryDTO obj : agentSummary) {
                    System.out.println("File " + obj.getCustomerCount());
                }
            }
        }
        
        class AgentSummaryDTO implements Serializable, Comparable<AgentSummaryDTO> {
        
            private Long id;
            private String agentName;
            private String agentCode;
            private String status;
            private Date createdDate;
            private Integer customerCount;
        
            AgentSummaryDTO() {
                customerCount = null;
            }
        
            AgentSummaryDTO(int customerCount) {
                this.customerCount = customerCount;
            }
        
            /**
             * @return the id
             */
            public Long getId() {
                return id;
            }
        
            /**
             * @param id
             *            the id to set
             */
            public void setId(Long id) {
                this.id = id;
            }
        
            /**
             * @return the agentName
             */
            public String getAgentName() {
                return agentName;
            }
        
            /**
             * @param agentName
             *            the agentName to set
             */
            public void setAgentName(String agentName) {
                this.agentName = agentName;
            }
        
            /**
             * @return the agentCode
             */
            public String getAgentCode() {
                return agentCode;
            }
        
            /**
             * @param agentCode
             *            the agentCode to set
             */
            public void setAgentCode(String agentCode) {
                this.agentCode = agentCode;
            }
        
            /**
             * @return the status
             */
            public String getStatus() {
                return status;
            }
        
            /**
             * @param status
             *            the status to set
             */
            public void setStatus(String status) {
                this.status = status;
            }
        
            /**
             * @return the createdDate
             */
            public Date getCreatedDate() {
                return createdDate;
            }
        
            /**
             * @param createdDate
             *            the createdDate to set
             */
            public void setCreatedDate(Date createdDate) {
                this.createdDate = createdDate;
            }
        
            /**
             * @return the customerCount
             */
            public Integer getCustomerCount() {
                return customerCount;
            }
        
            /**
             * @param customerCount
             *            the customerCount to set
             */
            public void setCustomerCount(Integer customerCount) {
                this.customerCount = customerCount;
            }
        
            @Override
            public int compareTo(AgentSummaryDTO arg0) {
        
                if (this.customerCount > arg0.customerCount)
                    return 0;
                else
                    return 1;
            }
        }
        

        【讨论】:

          【解决方案6】:

          answer by Jiri Kremser 可以进一步简化,这确实是 Java 8 的完整方式:

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

          这只是通过整数字段进行比较,并且由于Integer 实现了Comparable,所以效果很好。

          更清洁的解决方案可能是使用内置的comparingInt() 方法:

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

          当然,这可以通过静态导入sortcomparingInt来表达更短:

          sort(agentDtoList, comparingInt(AgentSummaryDTO::getCustomerCount));
          

          【讨论】:

            【解决方案7】:

            查看ComparatorCollections 类。

            一种简单的方法是在AgentSummaryDTO 中实现Comparable 接口,然后将列表传递给Collections.sort()

            如果您无法编辑AgentSummaryDTO,则需要一个比较器,如下所示:How to sort a List<Object> alphabetically using Object name field

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-04-06
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-03-01
              • 2011-02-18
              • 1970-01-01
              相关资源
              最近更新 更多