簡體   English   中英

Java 反轉映射

[英]Java invert map

我需要創建逆映射 - 選擇唯一值並為他們找到鍵。 似乎唯一的方法是迭代所有鍵/​​值對,因為 entrySet 返回 <key,value> 的集合,所以值不是唯一的?

地圖中的值可能不是唯一的。 但是如果它們(在你的情況下)你可以按照你在問題中寫的那樣做,並創建一個通用方法來轉換它:

private static <V, K> Map<V, K> invert(Map<K, V> map) {

    Map<V, K> inv = new HashMap<V, K>();

    for (Entry<K, V> entry : map.entrySet())
        inv.put(entry.getValue(), entry.getKey());

    return inv;
}

Java 8:

public static <V, K> Map<V, K> invert(Map<K, V> map) {
    return map.entrySet()
              .stream()
              .collect(Collectors.toMap(Entry::getValue, Entry::getKey));
}

用法示例:

public static void main(String[] args) {

    Map<String, Integer> map = new HashMap<String, Integer>();

    map.put("Hello", 0);
    map.put("World!", 1);

    Map<Integer, String> inv = invert(map);

    System.out.println(inv); // outputs something like "{0=Hello, 1=World!}"
}

旁注: put(.., ..)方法將返回鍵的“舊”值。 如果它不為null,則可能拋出new IllegalArgumentException("Map values must be unique")或類似的東西。

看看Google Guava BiMap

用法示例

Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");

Map<String, Integer> inverted = HashBiMap.create(map).inverse();

要在java 8中獲取給定映射的反轉形式:

public static <K, V> Map<V, K> inverseMap(Map<K, V> sourceMap) {
    return sourceMap.entrySet().stream().collect(
        Collectors.toMap(Entry::getValue, Entry::getKey,
           (a, b) -> a) //if sourceMap has duplicate values, keep only first
        );
}

用法示例

Map<Integer, String> map = new HashMap<Integer, String>();

map.put(1, "one");
map.put(2, "two");

Map<String, Integer> inverted = inverseMap(map);

似乎只有迭代所有鍵/​​值對的方法,因為entrySet返回的set值不是唯一的?

這至少是一種方式。 這是一個例子:

Map<Integer, String> map = new HashMap<Integer, String>();

map.put(1, "one");
map.put(2, "two");

Map<String, Integer> inverted = new HashMap<String, Integer>();

for (Integer i : map.keySet())
    inverted.put(map.get(i), i);

如果是非唯一值,則此算法會將找到的最后一個值映射到其密鑰。 (由於大多數地圖的迭代順序未定義,因此這應該與任何解決方案一樣好。)

如果您確實希望保留為每個鍵找到的第一個值,則可以將其更改為

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

我會給出另一個方法來給出一個額外的維度:EntrySet中的重復值

public static void main(String[] args) {

    HashMap<Integer, String> s = new HashMap<Integer, String>();
    s.put(1, "Value1");
    s.put(2, "Value2");
    s.put(3, "Value2");
    s.put(4, "Value1");

    /*
     * swap goes here
     */
    HashMap<String,List<Integer>> newMap = new HashMap<String, List<Integer>>();
    for (Map.Entry<Integer, String> en : s.entrySet()) {
        System.out.println(en.getKey() + " " + en.getValue());

        if(newMap.containsKey(en.getValue())){
            newMap.get(en.getValue()).add(en.getKey());
        } else {
            List<Integer> tmpList = new ArrayList<Integer>();
            tmpList.add(en.getKey());
            newMap.put(en.getValue(), tmpList);
        }
    }

    for(Map.Entry<String, List<Integer>> entry: newMap.entrySet()){
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
}

結果將是:

1 Value1
2 Value2
3 Value2
4 Value1
價值1 [1,4]
價值2 [2,3]

Apache Commons Collections還為雙向映射提供了BidiMap接口,以及多個實現。

BidiMap JavaDoc

用番石榴

Multimaps.transformValues(Multimaps.index(map.entrySet(), Map.Entry::getValue),
        Map.Entry::getKey)

你會得到一個multimap(基本上是一個列表的映射)作為回報。

如果您的值重復並且您需要將鍵存儲在列表中,您可以使用

val invertedMap = originalMap.entrySet().stream()
        .collect(Collectors.groupingBy(
                Map.Entry::getValue, 
                Collectors.mapping(Map.Entry::getKey, Collectors.toList()))
        );

您必須假設值可能相同,因為Map合約允許它。

在我看來,最好的解決方案在於使用包裝器。 它將包含原始值,並添加一個id。 它的hashCode()函數將依賴於id,並為原始值提供Getter。 代碼將是這樣的:

public class MapKey
{
    /**
     * A new ID to differentiate equal values 
     */
    private int _id;
    /**
     * The original value now used as key
     */
    private String _originalValue;

    public MapKey(String originalValue)
    {
        _originalValue = originalValue;
       //assuming some method for generating ids...
        _id = getNextId();
    }

    public String getOriginalValue()
    {
        return _originalValue;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + _id;
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MapKey other = (MapKey) obj;
        if (_id != other._id)
            return false;
        return true;
    }

    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append("MapKey value is ");
        sb.append(_originalValue);
        sb.append(" with ID number ");
        sb.append(_id);
        return sb.toString();
    }

反轉地圖將是這樣的:

public Map <MapKey, Integer> invertMap(Map <Integer, String> map)
{

     Map <MapKey, Integer> invertedMap = new HashMap <MapKey, Integer>();

   Iterator<Entry<Integer, String>> it = map.entrySet().iterator();

   while(it.hasNext())
   {
       //getting the old values (to be reversed)
       Entry<Integer, String> entry = it.next();
       Integer oldKey = entry.getKey();
       String oldValue = entry.getValue();

       //creating the new MapKey
       MapKey newMapKey = new MapKey(oldValue);
       invertedMap.put(newMapKey, oldKey);
   }

   return invertedMap;
}

打印這樣的值:

for(MapKey key : invertedMap.keySet())
       {
           System.out.println(key.toString() + " has a new value of " +  invertedMap.get(key));

       }

這些代碼都沒有經過測試,但我相信它是最好的解決方案,因為它使用OO繼承設計而不是“c”樣式檢查,並允許您顯示所有原始鍵和值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM