另一种随机打乱键值映射的方法:
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());
}
}
Edit:
如果您不想更改原始地图(因为以后需要它),您可以创建一个新地图:
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;
}
你并不真正想要看似随机的混合,但可以恢复(这很快就会变得复杂),但只需保留原始地图即可。如果这不合适,您需要更好地描述您的问题。
好的,您想使用密钥加密映射,提供另一个映射,然后再次解密。显然,随机洗牌在这里没有帮助,甚至伪随机也不好,因为它没有提供可靠的洗牌方法。在基本情况下,您的密钥将是我们映射的密钥之间的可逆映射。
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);
The map decrypted
现在应该和原来的地图一样了。
对于更大的键集,您需要找到一个方案来获得合适的
来自某些可输入键的键排列。