如果键中的列表包含其中的特定值,我需要获取键。
我唯一能想到的方法是迭代 HashMap 并为每个键值的列表进行循环,然后检查列表是否包含该值并返回键。像这样:
Map<String, List<MyItem>> map = new HashMap<>();
List<MyItem> list = new List<>();
list.add(new MyItem("Kim", 25);
list.add(new MyItem("Lee", 28);
map.put("Samsung", list);
String searchKeyWord = "Kim";
String myKey = getKeyByValue(map, searchKeyWord);
System.out.println("Found Key: " + myKey);
我不知道什么是最好的方法。
1.
public String getKeyByValue(Map<String, List<MyItem> map, String searchKeyWord) {
boolean flag = false;
String myKey = null;
for (Entry<String, List<MyItem>> e : map.entrySet()) {
String currentKey = e.getKey();
List<MyItem> myItemList = e.getValue();
Collections.sort(myItemList, this);
for (int i = 0 ; i < myItemList.size() ; i++) {
if (myItemList.get(i).name.equals(searchKeyWord)) {
myKey = currentKey;
flag = true;
}
if (flag) {
break;
}
}
if (flag) {
break;
}
}
return (flag ? myKey : null);
}
2.
public String getKeyByValue(Map map, String searchKeyWord){
boolean flag = false;
String myKey = null;
for(Entry<String, List<MyItem>> e: map.entrySet()){
String currentKey = e.getKey();
List<MyItem> myItemList = e.getValue();
Collections.sort(myItemList, this);
if(binarySearch(myItemList, searchKeyWord)){
myKey = currentKey;
flag = true;
}
}
if(flag) return myKey;
else null;
}
- 使用 HashMap 代替 List。
- 使用多值(Guava)
或者其他方法...
我应该改变数据结构吗?最好的搜索算法是什么?
最佳答案
评论中的解释:
private static String getKeyByValue(Map<String, List<MyItem>> map, String searchKeyWord) {
return map.entrySet().stream() //all entries in the map
.filter(e -> e.getValue().stream()
.anyMatch(i -> i.getName().equals(searchKeyWord))) //take only the ones which have searchKeyword in their list
.findAny() //take just one such entry
.map(Map.Entry::getKey) //change Entry to String (the key)
.orElse(null); //if there is no such entry, return null
}
正如@MCEmperor 建议的那样,您可以更改 String
至 Optional<String>
返回类型并去掉 .orElse(null);
.
或者如果你有很多元素,你可以通过使用像Map<String, Map<String, MyItem>>
这样的数据结构来避免扫描整个列表。像这样:
Map<String, Map<String, MyItem>> m = new HashMap<>();
Map<String, MyItem> items = Map.of(
"Kim", new MyItem("Kim", 25),
"Lee", new MyItem("Lee", 28)
);
m.put("Samsung", items);
String result = m.entrySet().stream()
.filter(e -> e.getValue().containsKey(searchKeyWord))
.findAny()
.map(Map.Entry::getKey)
.orElse(null);
关于java - 如果 Hash<String,List<Object>> 的 List 中存在元素,如何返回键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54896551/