java - 使用自定义比较器查找数组列表的最大值
问题描述
我有一个看起来像这样的早餐课程:
class Breakfast {
String[] fruits;
...
// Getter and Setter here
...
}
fruits 字段将始终是一个大小为 2 的数组,包含三个可能值之一: {"apple", "pear"} , {"apple", "grape"}, {"pear", "grape"}
我为这三个值设计了一个自定义顺序,如下所示:
String[] orderOne = {"apple", "pear"};
String[] orderTwo = {"apple", "grape"};
String[] orderThree = {"pear", "grape"};
我编写了自己的自定义比较器:
List<String[]> breakfastOrder = Arrays.asList(orderOne, orderTwo, orderThree);
Comparator<Breakfast> orderComparator = Comparator.comparing(b -> breakfastOrder.indexOf(new String[] {breakfast.getFruits()[0], breakfast.getFruits()[1]});
在处理早餐对象列表时,我希望找到“最大”水果组合。
换句话说,如果找到 {"pear", "grape"},则 {"pear", "grape"} 将是“Max”。如果没有找到 {"pear", "grape"},但找到了 {"apple", "grape"},则 {"apple", "grape"} 将是最大值。
当我有早餐对象列表时,如何找到“最大值”?流有一个最大功能,我可以将它与我的自定义比较器一起使用吗?
我在想这样的事情:
List<Breakfast> bList = //initialize the list
String[] max = bList.stream.max(orderComparator).get().getFruits();
如果 Java 11 中的任何部分发生了变化,请告诉我。另外,如果我的代码有任何问题或者我的逻辑/实现是否有缺陷,请告诉我。
解决方案
如果您可以覆盖equals/hashCode
for Breakfast
,则在此处简化(不要这样写等于):
@Override
public int hashCode() {
return Arrays.hashCode(fruits);
}
@Override
public boolean equals(Object other) {
Breakfast b = (Breakfast) other;
return Arrays.equals(b.getFruits(), getFruits());
}
您可以创建一个Map
并保留索引(如果需要,您可以将其视为 Comparator 强度):
Map<Breakfast, Integer> MAP = ImmutableMap.of(
new Breakfast(new String[]{"pear", "grape"}), 1,
new Breakfast(new String[]{"apple", "grape"}), 2,
new Breakfast(new String[]{"apple", "pear"}), 3);
并通过以下方式对它们进行排序:
Breakfast max = Collections.max(
yourListOfGrapes,
Comparator.comparingInt(b -> Optional.ofNullable(MAP.get(b)).orElse(0))
.reversed());
推荐阅读
- sql - 将具有逗号分隔的 varchar 值的表与 SQL Server 中另一个表的 Id 值连接起来
- jquery - 无法从外部 JSON 获取数据
- ios - 不需要的自我阴影
- flutter - 如何在flutter中从云Firestore中检索数据?
- c# - C# Json接口序列化父子
- angular - 我应该在角度上破坏什么?我该怎么办?
- python - 如何在 OpenCV 的 MLP 实现中设置“update_weights”?
- excel - 如何从共享文件夹中获取电子邮件正文?
- mocking - 使用模板基类模拟函数时出现“无趣的模拟函数调用”异常
- django - 从管理员端保存数据时如何显示错误消息。?我使用 models.model 来创建模型