【发布时间】: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
-
是的,我想通了。感谢您的所有帮助