Java invert map

前端 未结 8 1365
南旧
南旧 2020-11-30 09:33

I need create inverse map - select unique values and for them find keys. Seems that only way is to iterate all key/value pairs, because entrySet returns set of so value not

8条回答
  •  被撕碎了的回忆
    2020-11-30 10:21

    Seems that only way is to iterate all key/value pairs, because entrySet returns set of so value not unique?

    It's one way at least. Here's an example:

    Map map = new HashMap();
    
    map.put(1, "one");
    map.put(2, "two");
    
    Map inverted = new HashMap();
    
    for (Integer i : map.keySet())
        inverted.put(map.get(i), i);
    

    In case of non-unique values, this algorithm will map the last value found to it's key. (Since the iteration order is undefined for most maps, this should be as good as any solution.)

    If you really do want to keep the first value found for each key, you could change it to

    if (!inverted.containsKey(map.get(i)))
        inverted.put(map.get(i), i);
    

提交回复
热议问题