英文:
How can I sort by 2 keys from a list of dictionary?
问题
Sure, here's the translated code:
list = [{"tools": 12, "id": 1, "time": "2020-09-28"}, {"tools": 11, "id": 4, "time": "2021-10-24"}, {"tools": 18, "id": 3, "time": "2019-09-24"}]
#sort the list by "id" and "time"
英文:
list = [{"tools":12,"id":1,"time":"2020-09-28"}, {"tools":11,"id":4,"time":"2021-10-24"}, {"tools":18,"id":3,"time":"2019-09-24"}]
//sort the list by "id" and "time"
答案1
得分: 1
你可以使用Java 8的语法,使用以下Stream:
public static void main(String[] args) {
ArrayList<Sorting> list = new ArrayList<>();
List<Sorting> result = list.stream().sorted(Comparator.comparing(Sorting::getId).thenComparing(Sorting::getTime)).collect(Collectors.toList());
}
//Demo class
static class Sorting{
private Integer id;
private Integer tools;
private LocalDateTime time;
public Integer getId() {
return id;
}
public Integer getTools() {
return tools;
}
public LocalDateTime getTime() {
return time;
}
}
英文:
you can use Java8 grammar,Stream as follow:
public static void main(String[] args) {
ArrayList<Sorting> list = new ArrayList<>();
List<Sorting> result = list.stream().sorted(Comparator.comparing(Sorting::getId).thenComparing(Sorting::getTime)).collect(Collectors.toList());
}
//Demo class
static class Sorting{
private Integer id;
private Integer tools;
private LocalDateTime time;
public Integer getId() {
return id;
}
public Integer getTools() {
return tools;
}
public LocalDateTime getTime() {
return time;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论