Sort a Java collection object based on one field in it
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()
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));