'Sort a Java collection object based on one field in it

I have the following collection:

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

Where AgentSummaryDTO looks like this:

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

Now I have to sort the collection agentDtoList based on the customerCount field, how to achieve this?



Solution 1:[1]

here is my "1liner":

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

UPDATE for Java 8: For int datatype

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

or even:

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

For String datatype (as in comment)

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

..it expects getter AgentSummaryDTO.getCustomerCount()

Solution 2:[2]

The answer by Jiri Kremser can be simplified even further, which really is the full Java 8 way to do it:

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

This simply compares by the integer field, and works well since Integer implements Comparable.

An even cleaner solution might be to use the built-in comparingInt() method:

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

Of course, this could be expressed even shorter by statically importing sort and comparingInt:

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

Solution 3:[3]

Have a look at the Comparator and Collections classes.

A simple way would be to implement the Comparable interface in AgentSummaryDTO and then pass the list to Collections.sort().

If you can't edit AgentSummaryDTO, you need a Comparator as shown here: How to sort a List<Object> alphabetically using Object name field

Solution 4:[4]

Have a look at the code below.

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

Solution 5:[5]

UPDATE for Java 8. It works:

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

Solution 6:[6]

for anyone who looks for answer yet:

you can also sort your list with JAVA-8 Stream-API.

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

Solution 7:[7]

you can use this code

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

Solution 8:[8]

Suppose class Book having two attributes i.e. int pageNo and String bookName with getters and setters methods. And need to sort by page numbers, below is the code,

public class SortingBooks {
    public static void main(String[] args) {

        ArrayList<Book> books = new ArrayList<>();
        books.add(new Book(40, "My Dreams"));
        books.add(new Book(10, "Karma"));

        //sorting by page numbers
        books.sort((obj1, obj2) -> obj1.getPageNo()-obj2.getPageNo());

        //iterate list
        System.out.println(books.get(0).getPageNo() + "," + books.get(0).getBookName());

        //don't want to change original list then
        List<Books> sbook = books.stream()
                .sorted(Comparator.comparing(Book::getPageNo)).collect(Collectors.toList());
        System.out.println(sbook);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community
Solution 3 Community
Solution 4 Sandeep Yohans
Solution 5 ses
Solution 6 Sobhan
Solution 7 Ahmet Emre Kılınç
Solution 8 Uwe Allner