繁体   English   中英

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

[英]Java HashMap - How to simultaneously get and then remove a random entry from a HashMap?

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

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

也许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}

如果您要使用ConcurrentHashMap ,那么这将是一个原子操作。

HashMap返回和删除键值对的最佳方法是使用remove(key)方法。 此方法删除与key关联的条目并返回其对应的值。

Integer randomNumber = new Random().nextInt(10);
Map<Integer, String> map = new HashMap<>();
String valueOfRandomNumberKey = map.remove(randomNumber);

我会这样做:

Hashmap<Integer, Object> example;
int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());
example.getValue() //do something
example.remove(new Integer(randomNum));

据我了解,问题是这样的:给定一个HashMap你想要

  1. Map中当前关联的键中随机选择一个键;
  2. 从地图中删除该随机选择的键的关联;
  3. 返回直到最近才与该键关联的值

这是一个如何执行此操作的示例,以及一些小测试/演示例程:

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));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM