简体   繁体   中英

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

I was wondering if it is possible to get a random value from a HashMap and then straight after remove that key/value from the HashMap? I can't seem to find any method that works, would a different data structure be more appropriate for this?

Edit: I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.

Maybe Map#computeIfPresent would work in your case. From its documentation :

If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

If the remapping function returns null, the mapping is removed.

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

The above code outputs the following:

{1=One, 3=Three}

If you were to use a ConcurrentHashMap , then this would be an atomic operation.

The best way to both return and remove the key-value pair from a HashMap is by using the remove(key) method. This method removes the entry associated with the key and returns its corresponding value.

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

I would do it like this:

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

The problem, as I understand it, is this: given a HashMap you want to

  1. Choose a key at random from among the the keys currently associated in the Map ;
  2. Remove that association of that randomly chosen key from the map; and
  3. Return the value that had, until recently, been associated with that key

Here's an example of how to do this, along with some a little test/demonstration routine:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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