我如何从字典列表中按照两个键进行排序?

huangapple go评论85阅读模式
英文:

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&lt;Sorting&gt; list = new ArrayList&lt;&gt;();
    List&lt;Sorting&gt; 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;
    }
}

huangapple
  • 本文由 发表于 2020年7月26日 11:13:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63095717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定