【问题标题】:Picking a random Key and Value from a Map?从地图中选择随机键和值?
【发布时间】:2017-06-25 15:00:16
【问题描述】:

这是一个看似微不足道的编码任务,我似乎无法找到一个优雅的解决方案。也许这是周日下午的“愚蠢”事情,但我只是没有看到。

我有一个代表一组名称的地图:

  1. Map<String, Set<String>> namesForGroup;

内容看起来像这样:

1 {"Grp1": {"a", "b", "c", "d"},
2 "Grp2": {"e", "f", "g", "h"}}

我想要一种从该映射中提取随机键值对的优雅方法。例如:

1 ["Grp1", "a"]
2 ["Grp1", "d"]
3 ["Grp2", "g"]
4 ["Grp1", "c"]
5 ["Grp2", "e"]

不需要任何强随机性或所选值的任何均匀分布。只需要一个粗略的近似值,因为我只是为我正在为我在工作中编写的新功能编写的性能基准生成一些测试数据。

谢谢

【问题讨论】:

  • 你能澄清一下你卡在哪里了吗?
  • 我注意到你没有接受这个答案。有什么问题吗?

标签: java


【解决方案1】:

从集合中获取随机元素比从列表中获取随机元素要复杂一些,但它的工作原理如下:

private static String[] getRandomPair(Map<String, Set<String>> map) {
    Random random = new Random();

    String[] groups = map.keySet().toArray(new String[0]);
    String randomGroup = groups[random.nextInt(groups.length)];

    String[] names = map.get(randomGroup).toArray(new String[0]);
    String randomName = names[random.nextInt(names.length)];

    return new String[] { randomGroup, randomName };
}

使用示例:

public static void main(String[] args) {
    Map<String, Set<String>> namesForGroup = new HashMap<>();
    namesForGroup.put("Grp1", new HashSet<>(Arrays.asList("a", "b", "c", "d")));
    namesForGroup.put("Grp2", new HashSet<>(Arrays.asList("e", "f", "g", "h")));
    System.out.println(Arrays.toString(getRandomPair(namesForGroup)));
    System.out.println(Arrays.toString(getRandomPair(namesForGroup)));
    System.out.println(Arrays.toString(getRandomPair(namesForGroup)));
    System.out.println(Arrays.toString(getRandomPair(namesForGroup)));
}

打印例如:

[Grp2, e]
[Grp1, a]
[Grp2, e]
[Grp1, b]

【讨论】:

    【解决方案2】:

    您的问题与其他几个问题类似。重复链接可能是唯一的,因为您需要以嵌套方式两次查找集合的随机元素。您可以从地图的条目集中获取一个随机地图条目,获取该键,然后从该条目的值中获取一个随机元素,该值本身就是另一个集合。

    为此,如果我们创建一个可以在 Java Set 中找到随机元素的辅助方法可能会有所帮助。这是必需的,因为集合本质上是无序的。我们不能只访问某个索引,因为没有索引(好吧,也许在TreeSet 中这可能是有道理的,但在常规的Set 中则不然)。

    public static < T > T getRandomSetEntry(Set<T> set) {
        int size = set.size();
        int item = new Random().nextInt(size);
        int i = 0;
        for (T obj : set) {
            if (i == item)
                return obj;
            i++;
        }
    
        return null;
    }
    
    public static void main(String args[]) {
        Map<String, Set<String>> namesForGroup = new HashMap<>();
        Set<String> set1 = new HashSet<>();
        set1.add("a");
        set1.add("b");
        set1.add("c");
        set1.add("d");
        Set<String> set2 = new HashSet<>();
        set2.add("e");
        set2.add("f");
        set2.add("g");
        set2.add("h");
    
        namesForGroup.put("Grp1", set1);
        namesForGroup.put("Grp2", set2);
    
        Set<Map.Entry<String, Set<String>>> set = namesForGroup.entrySet();
        Map.Entry<String, Set<String>> entry = getRandomSetEntry(set);
        String key = entry.getKey();
        String value = getRandomSetEntry(entry.getValue());
        System.out.println("key: " + key + ", value: " + value);
    }
    

    演示在这里:

    Rextester

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 2012-04-12
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多