135*_*355 18 java sorting collections
我有以下集合:
Collection<AgentSummaryDTO> agentDtoList = new ArrayList<AgentSummaryDTO>();
Run Code Online (Sandbox Code Playgroud)
哪里AgentSummaryDTO
是这样的:
public class AgentSummaryDTO implements Serializable {
private Long id;
private String agentName;
private String agentCode;
private String status;
private Date createdDate;
private Integer customerCount;
}
Run Code Online (Sandbox Code Playgroud)
现在我必须agentDtoList
根据customerCount
字段对集合进行排序,如何实现这一目标?
Jir*_*ser 49
这是我的"1liner":
Collections.sort(agentDtoList, new Comparator<AgentSummaryDTO>(){
public int compare(AgentSummaryDTO o1, AgentSummaryDTO o2){
return o1.getCustomerCount() - o2.getCustomerCount();
}
});
Run Code Online (Sandbox Code Playgroud)
Java 8的UPDATE:对于int数据类型
Collections.sort(agentDtoList, (o1, o2) -> o1.getCustomerCount() - o2.getCustomerCount());
Run Code Online (Sandbox Code Playgroud)
甚至:
Collections.sort(agentDtoList, Comparator.comparing(AgentSummaryDTO::getCustomerCount));
Run Code Online (Sandbox Code Playgroud)
对于String数据类型(如注释中所示)
Collections.sort(list, (o1, o2) -> (o1.getAgentName().compareTo(o2.getAgentName())));
Run Code Online (Sandbox Code Playgroud)
..期待吸气 AgentSummaryDTO.getCustomerCount()
Sob*_*han 14
对于任何正在寻找答案的人:
您还可以使用 JAVA-8 Stream-API 对列表进行排序。
List<AgentSummaryDTO> sortedList = agentDtoList.stream()
.sorted(Comparator.comparing(AgentSummaryDTO::getCustomerCount).reversed())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
一种简单的方法是在其中实现Comparable接口AgentSummaryDTO
,然后将列表传递给Collections.sort()
.
如果无法编辑AgentSummaryDTO
,则需要一个Comparator,如下所示:如何使用Object name字段按字母顺序对List <Object>进行排序
Jiri Kremser的答案可以进一步简化,这完全是Java 8的完整方式:
Collections.sort(agentDtoList, Comparator.comparing(AgentSummaryDTO::getCustomerCount));
Run Code Online (Sandbox Code Playgroud)
这只是通过整数字段进行比较,并且自Integer
实现以来效果很好Comparable
.
更清晰的解决方案可能是使用内置comparingInt()
方法:
Collections.sort(agentDtoList, Comparator.comparingInt(AgentSummaryDTO::getCustomerCount));
Run Code Online (Sandbox Code Playgroud)
当然,这可以通过静态导入来表达更短sort
和comparingInt
:
sort(agentDtoList, comparingInt(AgentSummaryDTO::getCustomerCount));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
52606 次 |
最近记录: |