Is there a way to get the value of a HashMap randomly in Java?

前端 未结 13 2114
心在旅途
心在旅途 2020-11-30 03:45

Is there a way to get the value of a HashMap randomly in Java?

13条回答
  •  温柔的废话
    2020-11-30 04:32

    I wrote a utility to retrieve a random entry, key, or value from a map, entry set, or iterator.

    Since you cannot and should not be able to figure out the size of an iterator (Guava can do this) you will have to overload the randEntry() method to accept a size which should be the length of the entries.

    package util;
    
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    public class MapUtils {
        public static void main(String[] args) {
            Map map = new HashMap() {
                private static final long serialVersionUID = 1L;
                {
                    put("Foo", 1);
                    put("Bar", 2);
                    put("Baz", 3);
                }
            };
    
            System.out.println(randEntryValue(map));
        }
    
        static  Entry randEntry(Iterator> it, int count) {
            int index = (int) (Math.random() * count);
    
            while (index > 0 && it.hasNext()) {
                it.next();
                index--;
            }
    
            return it.next();
        }
    
        static  Entry randEntry(Set> entries) {
            return randEntry(entries.iterator(), entries.size());
        }
    
        static  Entry randEntry(Map map) {
            return randEntry(map.entrySet());
        }
    
        static  K randEntryKey(Map map) {
            return randEntry(map).getKey();
        }
    
        static  V randEntryValue(Map map) {
            return randEntry(map).getValue();
        }
    }
    

提交回复
热议问题