另一種方式爲隨機洗牌鍵 - 值映射:
public static <K,V> void shuffleMap(Map<K,V> map) {
List<V> valueList = new ArrayList<V>(map.values());
Collections.shuffle(valueList);
Iterator<V> valueIt = valueList.iterator();
for(Map.Entry<K,V> e : map.entrySet()) {
e.setValue(valueIt.next());
}
}
編輯:
如果你不想改變原有的地圖(因爲你需要它以後),您可以創建,而不是一個新問題:
public static <K,V> Map<K,V> shuffleMap(Map<K,V> map) {
List<V> valueList = new ArrayList<V>(map.values());
Collections.shuffle(valueList);
Iterator<V> valueIt = valueList.iterator();
Map<K,V> newMap = new HashMap<K,V>(map.size());
for(K key : map.keySet()) {
newMap.put(key, valueIt.next());
}
return newMap;
}
你真的不希望一個seemingl y隨機混合,這可以恢復(這很快變得複雜),但只保留你的原始地圖。如果這不合適,你需要更好地描述你的問題。
好的,你想通過使用密鑰加密映射,給出另一個映射,然後再解密它。很顯然隨機洗牌在這裏沒有什麼幫助,甚至僞隨機也不好,因爲它沒有提供可靠的重新洗牌方式。在基本情況下,您的密鑰將是映射關鍵字之間的可逆映射。
public static <K,V> Map<K,V> encryptMap(Map<K,V> plainMap, Map<K,K> key) {
Map<K,V> cryptoMap = new HashMap<K,V>(plainMap.size());
for(Map.Entry<K,V> entry : plainMap.entrySet()) {
cryptoMap.put(key.get(entry.getKey()), entry.getValue());
}
return cryptoMap;
}
解密的作用相同,實際上只使用密鑰的反向映射。
所以,當你有你的{100, 200, 300}
例如按鍵,這些按鍵中的任意排列是我們的「加密方案」有效的關鍵。 (只有6個可能的,這是不是很安全。)
Map sampleKey = new HashMap<Integer, Integer>();
sampleKey.put(100, 200);
sampleKey.put(200, 300);
sampleKey.put(300, 100);
Map sampleUnKey = new HashMap<Integer, Integer>();
for(Map.Entry<Integer, Integer> e : sampleKey) {
sampleUnKey.put(e.getValue(), e.getKey());
}
Map<Integer, String> data = new HashMap<Integer, String>();
data.put(100, "white");
data.put(200, "black");
data.put(300, "red");
System.out.println(data);
Map<Integer, String> encrypted = encryptMap(data, sampleKey);
System.out.println(encrypted);
Map<Integer, String> decrypted = encryptMap(data, sampleUnKey);
System.out.println(decrypted);
地圖decrypted
現在應該是一樣的原始地圖。
對於更大的按鍵組,你會想找到一個方案,從某些輸入能夠拿到鑰匙合適 排列鍵。
你所說的「混淆」是什麼意思? – marcog 2011-03-13 12:06:13
如果您不知道要執行哪種算法,很難確定哪種數據結構最適合您。 – 2011-03-13 12:06:51
@Max所有密鑰都是唯一的嗎? – Marnix 2011-03-13 12:07:31