-
尚方宝剑之说
也许Map#computeIfPresent会在你的情况下工作。从其文档中:如果指定键的值存在且非空,则尝试在给定键及其当前映射值的情况下计算新映射。如果重新映射函数返回 null,则删除映射。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}如果您要使用 a ConcurrentHashMap,那么这将是一个原子操作。
-
慕村225694
据我了解,问题是这样的:给定一个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)); }}
-
aluckdog
我会这样做:Hashmap<Integer, Object> example;int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());example.getValue() //do somethingexample.remove(new Integer(randomNum));