Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
可能重复: 有没有办法在 Java 中随机获取 HashMap 的值?
我想生成随机键并在 Hashmap 中显示它们的关联值,但不是所有键。例如,如果有 40 个键值对,我只想随机显示 10 个。
List keys = new ArrayList(theHashMap.keySet()); Collections.shuffle(keys); for (int i = 0; i < Math.min(keys.size(), 10); ++i) { map.get(keys[i]); }