Java按最高值排序,然后按最低键排序HashMap

Divadneb nahtan:

可以说我有一个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())获得最大的价值,但是我如何在柠檬和糖的总和最少的情况下找到最大的价值呢?

user7:

您可以创建映射条目的流,并使用该max方法来获取由比较器排序的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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章