Selecting random key and value sets from a Map in Java

后端 未结 8 1708

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

    Use reservoir sampling to select a list of random keys, then insert them into a map (along with their corresponding values in the source map.)

    This way you do not need to copy the whole keySet into an array, only the selected keys.

    public static <K, V>Map<K, V> sampleFromMap(Map<? extends K, ? extends V> source, int n, Random rnd) {
        List<K> chosenKeys = new ArrayList<K>();
        int count = 0;
        for (K k: source.keySet()) {
            if (count++ < n) {
                chosenKeys.add(k);
                if (count == n) {
                    Collections.shuffle(chosenKeys, rnd);
                }
            } else {
                int pos = rnd.nextInt(count);
                if (pos < n) {
                    chosenKeys.set(pos, k);
                }
            }
        }
        Map<K, V> result = new HashMap<K, V>();
        for (K k: chosenKeys) {
            result.put(k, source.get(k));
        }
        return Collections.unmodifiableMap(result);
    }
    
    0 讨论(0)
  • 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<Integer> alldocsId = new HashSet<>();
                for (int i=0;i<normalized.length;i++)
                {
                    String sql = "SELECT DISTINCT movieID FROM postingtbl WHERE term=?";
                    PreparedStatement prepstm = conn.prepareStatement(sql);
                    prepstm.setString(1,normalized[i]);
                    ResultSet rs = prepstm.executeQuery();
                    while (rs.next())
                    {
                        alldocsId.add(rs.getInt("MovieID"));
                    }
                    prepstm.close();
                }
    
            List<Integer> alldocIDlst = new ArrayList<>();
            Iterator it = alldocsId.iterator();
            while (it.hasNext())
            {
                alldocIDlst.add(Integer.valueOf(it.next().toString()));
            }
    
    0 讨论(0)
提交回复
热议问题