如何对 java 中的地图使用 group By?

How to use group By for a map in java?

我有一个包含地图的列表 List> 地图有两个键,一个是 id ,另一个是数量。我想根据金额键对列表进行降序排序,如果列表中两个元素的金额相同,则根据 id 对其进行排序。我该怎么做?


    List<Map<String, Object>> list = new ArrayList<>();
    Map<String, Object> hm = new HashMap<>();
    hm.put(id, 1);
    hm.put(amount, 25000);
    list.add(hm);

列表元素的索引 = 1, 2, 3 ,4 ,5 ,6

id = 1, 2, 3 ,4 ,5, 4 的值

金额的值 = 10000、450000、25000、45000、35000、75000

列表应该排序如下(列表索引) = 6, 4 (id 很大), 2, 5, 3, 1

我认为使用 CustomObject 而不是 Map 将帮助您以更简单的方式解决此问题。

自定义对象

//fell free to change data type of fields as per your requirement
public class CustomObject {
    private Integer id;
    private Integer amount;

    public CustomObject(Integer id, Integer amount) {
        this.id = id;
        this.amount = amount;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }
}

现在 List 将包含 Object 而不是 Map,这将使排序变得更加容易。

List<CustomObject> list=new ArrayList<>();
        CustomObject customObject1=new CustomObject(1,10000);
        CustomObject customObject2=new CustomObject(2,45000);
        CustomObject customObject3=new CustomObject(3,25000);
        CustomObject customObject4=new CustomObject(4,45000);
        CustomObject customObject5=new CustomObject(5,35000);
        CustomObject customObject6=new CustomObject(6,75000);

        list.add(customObject1);
        list.add(customObject2);
        list.add(customObject3);
        list.add(customObject4);
        list.add(customObject5);
        list.add(customObject6);

        // You can use thenComparing() as much as you required incase you want to compare with multiple field of your custom object
        // for your problem it has only two field
        Collections.sort(list, Comparator.comparing(CustomObject::getAmount)
                .thenComparing(CustomObject::getId).reversed());

        list.forEach(x->{

            System.out.println(x.getId()+" -->" +x.getAmount());
        });

输出:

6 -->75000
4 -->45000
2 -->45000
5 -->35000
3 -->25000
1 -->10000

有很多种可能,这个修改原列表:

Comparator<Map<String, Object>> sortByAmount = Comparator.comparing(m -> (int) m.get("amount"));
Comparator<Map<String, Object>> sortById = Comparator.comparing(m -> (int) m.get("id"));

list.sort(sortByAmount.reversed().thenComparing(sortById));

如果想保留原来的列表,可以使用流api:

list.stream().sorted(sortByAmount.reversed().thenComparing(sortById));