Selecting random key and value sets from a Map in Java

后端 未结 8 1713

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

    In some cases you might want to preserve an order you put the elements in the Set,
    In such scenario you can use, This 
    
    Set alldocsId = new HashSet<>();
                for (int i=0;i alldocIDlst = new ArrayList<>();
            Iterator it = alldocsId.iterator();
            while (it.hasNext())
            {
                alldocIDlst.add(Integer.valueOf(it.next().toString()));
            }
    

提交回复
热议问题