Java HashMap - 如何同时获取然后从 HashMap 中删除随机条目?

我想知道是否可以从 HashMap 中获取随机值,然后直接从 HashMap 中删除该键/值?我似乎找不到任何有效的方法,不同的数据结构会更适合这个吗?

编辑:我应该更清楚,我生成一个随机数,然后检索与该随机数对应的值。我需要返回该值,然后从地图中删除该条目。


白板的微信
浏览 304回答 3
3回答

尚方宝剑之说

也许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) -> {&nbsp; &nbsp; // `v` is equal to "Two"&nbsp; &nbsp; 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{&nbsp; &nbsp; private static <K, V> V removeRandomEntry(Map<K, V> map){&nbsp; &nbsp; &nbsp; &nbsp; Set<K> keySet = map.keySet();&nbsp; &nbsp; &nbsp; &nbsp; List<K> keyList = new ArrayList<>(keySet);&nbsp; &nbsp; &nbsp; &nbsp; K keyToRemove = keyList.get((int)(Math.random()*keyList.size()));&nbsp; &nbsp; &nbsp; &nbsp; return map.remove(keyToRemove);&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args){&nbsp; &nbsp; &nbsp; &nbsp; Map<String, String> map = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < 100; ++i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.put("Key" + i, "Value"+i);&nbsp; &nbsp; &nbsp; &nbsp; int pass = 0;&nbsp; &nbsp; &nbsp; &nbsp; while (!map.isEmpty())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Pass " + (++pass) + ": Removed: " + removeRandomEntry(map));&nbsp; &nbsp; }}

aluckdog

我会这样做:Hashmap<Integer, Object> example;int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());example.getValue() //do somethingexample.remove(new Integer(randomNum));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java