iT邦幫忙

1

在 HashMap 中 用value取key

假設我有

HashMap<Integer, Point> coord = new HashMap<>():
coord.put(coord.size(), new point(0, 0);

我可以用

Point point = coord.get(0);

取出他的值,那請問如果想要用值去取key該怎麼做呢?
這是我目前寫的

int set = coord.getKey(coord, new point(0, 0));

    private int getKey(HashMap map, Point target)
    {
        int index = 0;
        for (index=1;index<map.size();index++)
        {
            if (map.get(index).equals(target))
            {
                return index;
            }
        }
        return 0;
    }
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
3
theRookie
iT邦新手 1 級 ‧ 2019-12-04 09:19:05
最佳解答

如果數據結構在鍵和值之間具有多對一,則應遍歷map並選擇所有合適的key:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
    Set<T> keys = new HashSet<T>();
    for (Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            keys.add(entry.getKey());
        }
    }
    return keys;
}

如果是一對一關係,則可以返回第一個匹配的key:

public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
    for (Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}

Java 8寫法:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
    return map.entrySet()
              .stream()
              .filter(entry -> Objects.equals(entry.getValue(), value))
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());
}
小魚 iT邦大師 1 級 ‧ 2019-12-04 09:22:05 檢舉

用值去取Value,
似乎就失去了HashMap的存在意義了...

theRookie iT邦新手 1 級 ‧ 2019-12-04 09:27:59 檢舉

同感
但有人問能回答就回答

剛好目前有用到, 使用情境為紀錄每一次執行秒數, 取樣600次, 取得最多次的時間. 我用MAP 紀錄 秒數及執行次數, 取得最高值的次數後, 要得知這是幾秒.

1
海綿寶寶
iT邦大神 1 級 ‧ 2019-12-04 09:21:26

java 原生的 hashmap 只能 get value, 不支援 get key
(因為 hashmap 的原始定義就是key 不能重覆,而 value 可以重覆)
如果你堅心要 get key by value 還是有辦法
1.自己寫(要處理回傳 0,1,多筆 key 的三種情形,你目前只處理回傳1筆的情形)
2.用第三方函式庫, 看是要用 Apache 的還是 Google 的

以上說明及相關資源
全部在這篇網友問答裡都找得到

選我最佳解答

0
matthung
iT邦新手 5 級 ‧ 2019-12-16 08:29:17

同樣的value可能有多個key,會找到0到多個,可用List來裝。

/** 用value取得Map中的key */
private static <K, V> List<K> getKeys(Map<K, V> map, V value) {
    return map.entrySet().stream() // Stream<Set<Entry<K, V>>>
            .filter(e -> e.getValue().equals(value)) // 比對是否符合要找的value
            .map(Map.Entry::getKey) // 只拿key
            .collect(Collectors.toList()); // 塞到List
}

Java 在HashMap中用value取key

我要發表回答

立即登入回答