Java 是否有可能在没有循环的情况下获得未排序贴图的子贴图?

Java 是否有可能在没有循环的情况下获得未排序贴图的子贴图?,java,dictionary,collections,Java,Dictionary,Collections,我从另一个方法获得Map的实例 Map map = service.getMap(); 现在,我想从这个映射中获取任意10个元素 我知道我可以遍历Map.Entry,但我不喜欢这个决定 还有其他方法吗?显然,您想要的是地图中的10个任意元素。这将通过一个简单的Java 8习惯用法提供: set.entrySet().stream().limit(10).collect(toList()); 如果您只需要值,我建议采用以下方法: Map map = service.getMap(); Obje

我从另一个方法获得
Map
的实例

Map map = service.getMap();
现在,我想从这个映射中获取任意10个元素

我知道我可以遍历
Map.Entry
,但我不喜欢这个决定


还有其他方法吗?

显然,您想要的是地图中的10个任意元素。这将通过一个简单的Java 8习惯用法提供:

set.entrySet().stream().limit(10).collect(toList());

如果您只需要值,我建议采用以下方法:

Map map = service.getMap();
Object[] array= map.entrySet().toArray();
Arrays.copyOfRange(array, 0, 10);
还是泛型

Map<Key, Value> map = service.getMap();
Map.Entry<Key, Value>[] array = (Map.Entry<Key, Value>[]) map.entrySet().toArray(new Map.Entry[0]);
Arrays.copyOfRange(array, 0, 10);
Map-Map=service.getMap();
Map.Entry[]数组=(Map.Entry[])Map.entrySet().toArray(新的Map.Entry[0]);
copyOfRange(数组,0,10);

Map.Entry有
getKey()
getValue()

您可以使用一个中间列表来保存键,然后从中选择随机元素。例如,此代码创建一个包含15个元素的映射,然后从中随机选择10个元素:

public static void main(String[] args) throws Exception {
    Map<Integer, String> map = new HashMap<>();
    for(int x = 0; x < 15; x++) {
        map.put(x, "val: " + String.valueOf(x));
    }

    List<Integer> keyList = new ArrayList<>(map.keySet());
    Map<Integer, String> randomMap = new HashMap();
    for(int x = 0; x < 10 && !keyList.isEmpty(); x++) {
        Integer key = keyList.remove(new Random().nextInt(keyList.size()));
        randomMap.put(key, map.get(key));
    }
    System.out.println(randomMap);
}
publicstaticvoidmain(字符串[]args)引发异常{
Map Map=newhashmap();
对于(int x=0;x<15;x++){
map.put(x,“val:+String.valueOf(x));
}
List keyList=newarraylist(map.keySet());
Map randomMap=新的HashMap();
对于(intx=0;x<10&&!keyList.isEmpty();x++){
Integer key=keyList.remove(new Random().nextInt(keyList.size());
randomMap.put(key,map.get(key));
}
System.out.println(随机映射);
}

这还有一个优点,就是它实际上是在选择随机元素,而不是只返回前10个元素的其他解决方案,每次都会返回相同的10个元素。

您需要10个真正随机的元素吗?愚蠢的想法-你可以提取所有元素,洗牌-选择前10个。更重要的是-为什么需要它?鉴于你不能对地图的键使用随机访问,ovbious的解决方法是在
列表中收集键,收集。shuffle()
列表
并获取前10个元素…@神秘随机不是目的。没有重复的元素你使用的是什么类型的地图?是hashmap/treemap等吗?然后你想使用“任意”这个词。@gstackoverflow entrySet有键和值。@Kate欢迎使用StackOverflow,我随意添加了泛型,这样你就可以看到其中有键和值。下面代码执行的结果是一个Map数组。entry根据我的问题,结果应该是Map