Search code examples
javahashmap

How to get few random keys from HashMap


I have a map with titles. I want to print 10 random keys from my hashmap.

For example my map (String, Object) contains 100 pairs: "A, new Object(...)", "B, ...", "C, ..." etc.

I want to get 10 random keys from this map and append it to one string.

So my string should looks like: "A\nD\nB".


Solution

  • A quick way to get random 10 keys without repetition is putting the keys in a list and using Collections.shuffle to shuffle the list.

    Map<String, Object> map = ...yourmap
    ArrayList<String> keys = new ArrayList<>(map.keySet());
    Collections.shuffle(keys);
    List<String> randomTenKeys = keys.subList(0, 10);
    

    Creating a list of all keys and shuffling it is not the most efficient thing you can do. You can do it in a single pass with a reservoir sampling algorithm. I haven't looked into it but you can probably find an implementation in some Apache or Guava library.