56

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?

Magnilex
  • 11,584
  • 9
  • 62
  • 84
skmaran.nr.iras
  • 8,152
  • 28
  • 81
  • 116
  • 1
    If you had used those tags to search in javadoc, you could have hit this: http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator) – Vikdor Sep 22 '12 at 09:58

8 Answers8

111

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

Jiri Kremser
  • 12,471
  • 7
  • 45
  • 72
  • 1
    I used return agentSummary1.getCustomerCount().compareTo(agentSummary2.getCustomerCount()); – skmaran.nr.iras Sep 28 '12 at 04:51
  • What if i need to sort same example with agentname instead of customercount? I need to sort on a string field. please suggest – Tanu Garg Mar 24 '16 at 18:41
  • 6
    @TanuGarg instead of `return o1.getCustomerCount() - o2.getCustomerCount();`, you would have `o1.getAgentName().compareTo(o2.getAgentName())` – Jiri Kremser Mar 24 '16 at 19:52
  • based on the results of the `.compareTo` it can return `0` if the compared strings are the same, negative value if the first one is bigger and positive value otherwise. It uses the lexicographical ordering for strings. Then this results are used by the sorting algorithm in Java (which happens to be Merge sort) – Jiri Kremser Sep 24 '18 at 16:55
  • Will `Collections.sort(agentDtoList, (o1, o2) -> Integer.compare(o1.getCustomerCount(), o2.getCustomerCount()));` work? – Pierre Jul 16 '19 at 13:45
  • How to sort in descending order using this syntax `Collections.sort(agentDtoList, Comparator.comparing(AgentSummaryDTO::getCustomerCount));` – karthik_varma_k Sep 19 '19 at 11:28
  • 2
    @karthik_varma_k `Collections.sort(agentDtoList, Comparator.comparing(AgentSummaryDTO::getCustomerCount).reversed());` – Jiri Kremser Sep 19 '19 at 15:39
  • there's no need for parentheses around lambda body in third example (makes it a bit easier to read :) ) – skwisgaar Oct 09 '20 at 15:28
  • Even further : `agentDtoList.sort(Comparator.comparing(AgentSummaryDTO::getCustomerCount));` – Adama Traore Sep 20 '22 at 08:17
14

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));
Community
  • 1
  • 1
Magnilex
  • 11,584
  • 9
  • 62
  • 84
12

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());
Sobhan
  • 1,280
  • 1
  • 18
  • 31
7

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

Community
  • 1
  • 1
exic
  • 2,220
  • 1
  • 22
  • 29
3

UPDATE for Java 8. It works:

Collections.sort(agentDtoList, (o1, o2) -> o1.getCustomerCount() - o2.getCustomerCount());
ses
  • 13,174
  • 31
  • 123
  • 226
Whoami
  • 31
  • 2
2

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;
    }
}
Sandeep Yohans
  • 929
  • 1
  • 14
  • 36
dareurdream
  • 241
  • 4
  • 13
1

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);
    }
}
Uwe Allner
  • 3,399
  • 9
  • 35
  • 49
-1

you can use this code

agentDtoList.sort((t1, t2) -> t1.getCustomerCount());
Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42