You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java整数多条件排序需求:按数值排序,相等时按变量名字母序

解决方案

核心思路是把变量名和对应的数值绑定在一起,这样排序后依然能关联到原变量名,具体实现可以用Java 16+的Record(简洁高效)或者自定义类,再结合自定义排序规则完成需求。

方法1:使用Java 16+ Record实现

public void doSomething(int carrots, int mushrooms, int salads, int tomatoes) {
    // 定义Record存储变量名和对应数值
    record Ingredient(String name, int amount) {}

    // 将所有变量包装成Ingredient实例,存入列表
    List<Ingredient> ingredients = List.of(
        new Ingredient("carrots", carrots),
        new Ingredient("mushrooms", mushrooms),
        new Ingredient("salads", salads),
        new Ingredient("tomatoes", tomatoes)
    );

    // 执行过滤、排序、输出
    ingredients.stream()
        .filter(ing -> ing.amount() != 0) // 过滤数值为0的项
        .sorted((a, b) -> {
            // 先按数值降序排序
            int amountCompare = Integer.compare(b.amount(), a.amount());
            if (amountCompare != 0) {
                return amountCompare;
            }
            // 数值相等时,按变量名字母升序排序
            return a.name().compareTo(b.name());
        })
        .forEach(ing -> System.out.printf("%s: %d%n", ing.name(), ing.amount()));
}

方法2:兼容Java 16以下版本(自定义类)

如果你的Java版本低于16,无法使用Record,可以自定义一个内部类来封装变量名和数值:

public void doSomething(int carrots, int mushrooms, int salads, int tomatoes) {
    // 自定义内部类,存储变量名和数值
    class Ingredient {
        private final String name;
        private final int amount;

        public Ingredient(String name, int amount) {
            this.name = name;
            this.amount = amount;
        }

        public String getName() { return name; }
        public int getAmount() { return amount; }
    }

    // 初始化变量列表
    List<Ingredient> ingredients = new ArrayList<>();
    ingredients.add(new Ingredient("carrots", carrots));
    ingredients.add(new Ingredient("mushrooms", mushrooms));
    ingredients.add(new Ingredient("salads", salads));
    ingredients.add(new Ingredient("tomatoes", tomatoes));

    // 过滤0值
    ingredients.removeIf(ing -> ing.getAmount() == 0);

    // 自定义排序规则
    ingredients.sort((a, b) -> {
        int amountCompare = Integer.compare(b.getAmount(), a.getAmount());
        if (amountCompare != 0) {
            return amountCompare;
        }
        return a.getName().compareTo(b.getName());
    });

    // 按格式输出
    for (Ingredient ing : ingredients) {
        System.out.println(ing.getName() + ": " + ing.getAmount());
    }
}

关键说明

  • 绑定变量名与数值:不管用Record还是自定义类,核心都是把变量名(字符串)和对应的int值封装在一起,解决了单独存储数值无法映射回原变量名的问题。
  • 排序规则优先级:先按数值排序(示例中为降序,若需要升序,调换Integer.compare中参数顺序即可),数值相等时再按变量名的自然字母顺序排序。
  • 过滤0值:通过filter(Stream流方式)或removeIf(集合直接操作)实现,符合你只输出非0项的需求。

内容的提问来源于stack exchange,提问作者casual Coffee enjoyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 20:40:27