【问题标题】:Java sort HashMap by highest value, then lowest keyJava 按最大值排序HashMap,然后是最低键
【发布时间】:2020-06-08 04:34:39
【问题描述】:

假设我有一个HashMap<Recipe, Integer>,其中 Recipe 是一个具有 2 个整数参数的类。我们可以称它们为柠檬和糖。我想在 HashMap 中获取具有最高对应值的键(这是一个配方)。作为二级排序方法,以防它包含多个具有相同值的食谱。它应该返回具有最低糖和柠檬总和的食谱。

例如。

HashMap<Recipe, Integer> recipes = new HashMap<>();
recipes.put(new Recipe(5, 3), 10); // 5 is lemons, 3 is sugar
recipes.put(new Recipe(8, 8), 15);
recipes.put(new Recipe(1, 2), 15);
Recipe bestRecipe - recipes.getBestRecipe();
// bestRecipe.getLemons() would be 1
// bestRecipe.getSugar() would be 2
// because it has the highest value (15) with the lowest sum of sugar and lemons (1+2=3)

我该怎么做呢?我知道我可以使用 Collections.max(recipes.values()) 获得最大值,但我如何才能找到柠檬和糖的总和最少的最大值?

【问题讨论】:

  • 你的Recipe 对象有equals 和hashcode 吗?比较的标准是什么?
  • 预期的输出是什么??
  • 只要写一个Comparator,根据你的逻辑比较Map.Entry对象。
  • 你可以使用这个答案:stackoverflow.com/a/4805676/259889
  • 是的,我想通了。感谢您的所有帮助

标签: java hashmap


【解决方案1】:

您可以创建一个映射条目流并使用max 方法获取由比较器排序的最大元素。

比较器逻辑如下:

  1. 它按地图的值排序。
  2. 如果出现平局,它反向按食谱中柠檬和糖的总和进行排序。这意味着这些值将按从大到小排序。

Optional<Recipe> bestRecipe = recipes.entrySet()
                .stream()
                .max(Comparator.comparingInt((Map.Entry<Recipe, Integer> e) -> e.getValue())
                        .thenComparing(e -> e.getKey().getSugar() + e.getKey().getLemons(), 
                            Comparator.reverseOrder()))
                .map(Map.Entry::getKey);

【讨论】:

  • 非常感谢您花时间解释它
【解决方案2】:

您可以流式传输地图并编写比较器进行排序,然后获取第一个元素

recipes.entrySet().stream()
        .sorted((e1, e2) -> {
             int v = e2.getValue().compareTo(e1.getValue());
             if(v!=0) return v;
             Integer a = (e1.getKey().getLemons() + e1.getKey().getSuger());
             Integer b = (e2.getKey().getLemons() + e2.getKey().getSuger());
             return Integer.compare(a,b);
         })
        .map(Map.Entry::getKey)
        .findFirst().get();

【讨论】:

  • 这个似乎正好相反哈哈。不过不用担心,Robby Cornelissen 的回答奏效了。对我来说,它似乎返回了最低值,而糖+柠檬是 40,这是最高的
  • @divadnebnahtan 抱歉,现在支票不全
猜你喜欢
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-23
  • 2019-06-03
  • 2016-11-03
相关资源
最近更新 更多