如何从HashMap中获取几个随机键

huangapple go评论73阅读模式
英文:

How to get few random keys from HashMap

问题

我有一个带有标题的地图。我想从我的哈希地图中随机选择 10 个键进行打印。

例如,我的地图(String,Object)包含 100 对:"A,new Object(...)","B,...","C,..."等等。

我想从这个地图中获取 10 个随机键,并将其附加到一个字符串中。

所以我的字符串应该看起来像:"A\nD\nB"。

英文:

I have a map with titles. I want to print 10 random keys from my hashmap.

For example my map (String, Object) contains 100 pairs: "A, new Object(...)", "B, ...", "C, ..." etc.

I want to get 10 random keys from this map and append it to one string.

So my string should looks like: "A\nD\nB".

答案1

得分: 4

获取10个不重复随机键的快速方法是将键放入列表中,然后使用Collections.shuffle来对列表进行洗牌。

Map<String, Object> map = ...yourmap
ArrayList<String> keys = new ArrayList<>(map.keySet());
Collections.shuffle(keys);
List<String> randomTenKeys = keys.subList(0, 10);

创建包含所有键并对其进行洗牌不是最高效的方法。你可以使用蓄水池抽样算法在一次遍历中完成。我没有深入研究过,但你可能可以在一些 Apache 或 Guava 库中找到实现。

英文:

A quick way to get random 10 keys without repetition is putting the keys in a list and using Collections.shuffle to shuffle the list.

Map&lt;String, Object&gt; map = ...yourmap
ArrayList&lt;String&gt; keys = new ArrayList&lt;&gt;(map.keySet());
Collections.shuffle(keys);
List&lt;String&gt; randomTenKeys = keys.subList(0, 10);

Creating a list of all keys and shuffling it is not the most efficient thing you can do. You can do it in a single pass with a reservoir sampling algorithm. I haven't looked into it but you can probably find an implementation in some Apache or Guava library.

答案2

得分: 1

以下是翻译好的代码部分:

import java.util.*;
import java.util.stream.IntStream;

public class Test {
    public static void main(String [] args){
        Map<String, Object> map = new HashMap<>();
        //您可以使用for循环来创建一个String,Integer类型的映射。
        IntStream.rangeClosed(0, 9).forEach(i -> map.put(i + "", i));//包含10个数字的映射。

        List<String> keys = getRandomKeys(map, 3);
        String allKeys = combineKeys(keys, "\n");
        System.out.println(allKeys);
    }

    public static List<String> getRandomKeys(Map<String, Object> map, int keyCount) {
        List<String> keys = new ArrayList<>(map.keySet());

        for(int i = 0; i < map.size()-keyCount; i++){
            int idx = (int) ( Math.random() *  keys.size() );
            keys.remove(idx);
        }
        return keys;
    }

    public static String combineKeys(List<String> keys, String separator){
        String all = "";

        for(int i = 0; i < keys.size() - 1; i++){
            all = all + keys.get(i) + separator;
        }

        all += keys.get(keys.size()-1);//最后一个元素不需要分隔符。

        return all;
    }
}

希望这些内容对您有所帮助!如有需要,请随时提问。

英文:

Joni's answer is quite good and short. But, here is a fully working example if you'd like. I split your problem into two methods - one to return a list of randomly selected keys and another to print keys in whichever way you like. You could combine the two methods into one. But, its better to keep them separate.

import java.util.*;
import java.util.stream.IntStream;
public class Test {
public static void main(String [] args){
Map&lt;String, Object&gt; map = new HashMap&lt;&gt;();
//You can use for loop instead to make a map of String, Integer. 
IntStream.rangeClosed(0, 9).forEach(i -&gt; map.put(i +&quot;&quot;, i));//Map of 10 numbers.
List&lt;String&gt; keys = getRandomKeys(map, 3);
String allKeys = combineKeys(keys, &quot;\n&quot;);
System.out.println(allKeys);
}
public static List&lt;String&gt; getRandomKeys(Map&lt;String, Object&gt; map, int keyCount) {
List&lt;String&gt; keys = new ArrayList&lt;&gt;(map.keySet());
for(int i = 0; i &lt; map.size()-keyCount; i++){
int idx = (int) ( Math.random() *  keys.size() );
keys.remove(idx);
}
return keys;
}
public static String combineKeys(List&lt;String&gt; keys, String separator){
String all = &quot;&quot;;
for(int i = 0; i &lt; keys.size() - 1; i++){
all = all + keys.get(i) + separator;
}
all += keys.get(keys.size()-1);//last element does not need separator.
return all;
}
}

答案3

得分: 1

这是对Joni的回答的一个补充回答。使用String:join来连接randomTenKeys

以下是Joni的回答

Map<String, Object> map = ...yourmap
ArrayList<String> keys = new ArrayList<>(map.keySet());
Collections.shuffle(keys);
List<String> randomTenKeys = keys.subList(0, 10);

补充回答是:

String joinedKeys = String.join("\n", randomTenKeys);
英文:

This is a complementary answer to Joni's answer. Use String:join to join the randomTenKeys.

Given below is Joni's answer:

Map&lt;String, Object&gt; map = ...yourmap
ArrayList&lt;String&gt; keys = new ArrayList&lt;&gt;(map.keySet());
Collections.shuffle(keys);
List&lt;String&gt; randomTenKeys = keys.subList(0, 10);

and the complementary answer is:

String joinedKeys = String.join(&quot;\n&quot;, randomTenKeys);

答案4

得分: 1

HashMap存储的值已经是无序的,它是随机的。
你可以直接使用

for(Map.Entry entry : map.entrySet())
str.append(entry.getKey()+" "+entry.getValue());

然而,如果你希望每次都有新的顺序,你可以对数据进行洗牌。
要进行洗牌,你需要将所有的键获取到一个数组或列表中,
然后你可以对该列表进行洗牌,并遍历该列表以从HashMap中获取值。

英文:

HashMap Stores the values already in unsorted order it is random.
you can directly use

for(Map.Entry entry : map.entrySet())
str.append(entry.getKey()+&quot; &quot;+entry.getValue());

however if you want new order every time you can shuffle your data.
For Shuffle you need to get all keys in a array or list
Then you can shuffle that list and iterate over that list to get values from hashmap

答案5

得分: 0

Set<String> keys = myMap.keySet();
String combined = "";
for (int i = 0; i < 10; i++) {
   int random = (int)(Math.random() * keys.size());
   String key = keys.get(random);
   combined += key + "\n";
   keys.remove(random);
}
英文:
Set&lt;String&gt; keys = myMap.keySet();
String combined = &quot;&quot;;
for (int i=0; i&lt;10; i++)
{
int random = (int)(Math.random() * keys.size());
String key = keys.get(random);
combined += key + &quot;\n&quot;;
keys.remove(random);
}

huangapple
  • 本文由 发表于 2020年4月8日 01:47:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/61086200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定