我想知道是否有可能从HashMap中获得一个随机值,然后立即从HashMap中删除该键/值? 我无法找到任何可用的方法,是否有其他数据结构更适合此操作?
编辑:我应该说得更清楚,我生成一个随机数,然后检索与该随机数相对应的值。 我需要返回该值,然后从映射中删除该项。
编辑:我应该说得更清楚,我生成一个随机数,然后检索与该随机数相对应的值。 我需要返回该值,然后从映射中删除该项。
从HashMap
中返回并删除键值对的最佳方法是使用remove(key)
方法。该方法会删除与key
相关联的条目,并返回其对应的值。
Integer randomNumber = new Random().nextInt(10);
Map<Integer, String> map = new HashMap<>();
String valueOfRandomNumberKey = map.remove(randomNumber);
Map#computeIfPresent
适用于你的情况。根据文档描述:var map = new HashMap<Integer, String>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.computeIfPresent(2, (k, v) -> {
// `v` is equal to "Two"
return null; // Returning `null` removes the entry from the map.
});
System.out.println(map);
{1=One, 3=Three}
ConcurrentHashMap
,那么这将是一个原子操作。Hashmap<Integer, Object> example;
int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());
example.getValue() //do something
example.remove(new Integer(randomNum));
HashMap
,你想要:
Map
相关联的键中随机选择一个键;以下是如何执行此操作的示例,以及一些小测试/演示程序:
public class Main
{
private static <K, V> V removeRandomEntry(Map<K, V> map){
Set<K> keySet = map.keySet();
List<K> keyList = new ArrayList<>(keySet);
K keyToRemove = keyList.get((int)(Math.random()*keyList.size()));
return map.remove(keyToRemove);
}
public static void main(String[] args){
Map<String, String> map = new HashMap<>();
for(int i = 0; i < 100; ++i)
map.put("Key" + i, "Value"+i);
int pass = 0;
while (!map.isEmpty())
System.out.println("Pass " + (++pass) + ": Removed: " + removeRandomEntry(map));
}
}
HashMap
上的.keySet
方法获取所有现有键作为Set
;使用键集上的.toArray
方法获取键的数组。生成介于零和键数组大小之间的随机数;在该索引处获取键k
,并在HashMap
上使用.remove(k)
。 - Kevin Anderson