如果Hash <string,list <object >>中的List中存在某个元素,如何返回键?

时间:2019-02-27 01:13:51

标签: java algorithm sorting

如果密钥列表中包含特定值,我需要获取密钥。

我唯一想到的方法是迭代HashMap,并为每个键的值的List进行for循环,然后检查List是否包含该值并返回键。像这样:

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;
}
  1. 使用HashMap代替List。
  2. 使用多值(番石榴)

或其他方法...

我应该更改数据结构吗?最好的搜索算法是什么?

1 个答案:

答案 0 :(得分:3)

注释说明:

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);