java - 有没有更好的方法从列表中查找内容?
问题描述
我有以下帮助函数,它查看两个列表并基于一个字段。确定要返回列表中的哪些对象。正在寻找的对象是列表 A 中的 5 种类型之一,或列表 b 中的 2 种类型之一……但是,如果存在不止一种类型(很可能),则类型需要优先于其他...因此,如果列表 A 和 B 中都存在 TYPE_4,则需要优先考虑列表 A 中的那个。此外,如果列表 A 中同时存在 TYPE_1 和 TYPE_2,则它们的首选项是给 TYPE_1。IF 列表 B 包含 TYPE_1、TYPE_2。或 TYPE_3,根本不考虑它们...只应考虑列表 B 中的 TYPE_4 和 TYPE_5。
private static SomeObject getFavoredObject(
List<SomeObject> listA,
List<SomeObject> listb)
{
Map<String, SomeObject> typeMap = new HashMap<>();
listA.forEach(a -> typeMap.put("A " + a.getType(), a));
listB.forEach(a -> typeMap.put("B " + a.getType(), a));
if (typeMap.containsKey("A TYPE_1")) {
return typeMap.get("A Type_1");
}
if (typeMap.containsKey("A TYPE_2")) {
return typeMap.get("A TYPE_2");
}
if (typeMap.containsKey("A TYPE_3")) {
return typeMap.get("A TYPE_3");
}
if (typeMap.containsKey("A TYPE_4")) {
return typeMap.get("A TYPE_4");
}
if (typeMap.containsKey("A TYPE_5")) {
return typeMap.get("A TYPE_5");
}
if (typeMap.containsKey("B TYPE_4")) {
return typeMap.get("B TYPE_4");
}
if (typeMap.containsKey("B TYPE_5")) {
return typeMap.get("B TYPE_5");
}
return new Address();
}
困扰我的是 if 语句的序列......当然有更优雅的方式来处理这个问题。我几乎有一个使用地图的解决方案,我在将列表 A 和列表 B 添加到 typeMap 之前对它们进行了排序,但是第二次我这样做了,typeMap 没有排序......所以我最终拉错了一个(嘘)。一个多小时以来,我一直在努力解决这个问题,现在是星期五,一天结束了。我要去喝啤酒了。如果有人能想出一些更优雅的东西,不涉及大量代码,减少“重复代码”(我们使用声纳,早期报告显示这个代码段有问题)或者可以指出我朝着正确的方向前进,我将不胜感激。
解决方案
代码的中心部分可以写成一个数组循环。
// This array should probably be static and final
// outside this method, assuming a fixed set of keys
String[] keys = {
"A TYPE_1", "A TYPE_2", ...
"B TYPE_4", "B TYPE_5
};
for (String key : keys)
if (typeMap.containsKey(key)
return typeMap.get(key);
另外,假设 SomeObject 永远不会为空,我会避免双重地图访问:
for (String key : keys) {
SomeObject obj = typeMap.get(key);
if (obj != null) return obj;
}
推荐阅读
- visual-studio - Chrome 更新搞砸了我用 VS 进行的调试
- r - 索引 R 中的非 NA 值以子集 R 中的新数据帧
- excel - 合并仅用变量引用的连续单元格
- excel - 如何将 dd/mm/yyyy HHMM 批量转换为 dd/mm/yyyy HH:MM
- python - Pandas DataFrame 中的链接元素
- python - Selenium,解决验证码后检测到无法绕过页面[安全]
- typescript - 类型 ts 上不存在属性
- python - 在字典列表/嵌套字典python中搜索和过滤
- react-native - 是否可以将函数的值传递给 react-native 中的组件?
- javascript - 我怎样才能使我选择的表格中的优秀?