Selecting random key and value sets from a Map in Java

后端 未结 8 1722

I want to get random keys and their respective values from a Map. The idea is that a random generator would pick a key and display that value. The tricky part is that both k

8条回答
  •  感动是毒
    2020-12-05 13:35

    I would copy the Map into an array and select the entry you want at random. This avoid the need to also lookup the value from the key.

    Map x = new HashMap();
    Map.Entry[] entries = x.entrySet().toArray(new Map.Entry[0]);
    Random rand = new Random();
    
    // call repeatedly
    Map.Entry keyValue = entries[rand.nextInt(entries.length)];
    

    If you want to avoid duplication, you can randomize the order of the entries

    Map x = new HashMap();
    List> entries = new ArrayList> (x.entrySet());
    Collections.shuffle(entries);
    for (Map.Entry entry : entries) {
        System.out.println(entry);
    }
    

提交回复
热议问题