Selecting random key and value sets from a Map in Java

后端 未结 8 1720

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:33

    if your keys are integer, or something comparable, you can use TreeMap to do that.

    TreeMap treeMap = new TreeMap<>();
    int key = RandomUtils.ranInt(treeMap.lastKey());
    int value = treeMap.ceilingKey(key);
    

提交回复
热议问题