另一种方式为随机洗牌键 - 值映射:
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