我有一个LinkedHashSet
,也就是有序集。我正在尝试找到一个函数,它只返回集合的一个子集,即集合的前20个元素。我知道我可以通过创建一个新的集合,然后使用第一个集合的迭代来填充,但我希望有更简洁的东西。
我也看了一下Google的Guava库,但看不到我想要什么。
发布于 2012-10-19 03:36:22
在Guava:
Set<Integer> subset = ImmutableSet.copyOf(Iterables.limit(set, 20));
请注意,Iterables.limit()
是延迟计算的,因此只创建了一个额外的集合。
发布于 2015-11-16 22:41:53
使用流和收集器的解决方案:
Set<Integer> subSet = set.stream()
// .skip(10) // Use this to get elements later in the stream
.limit(20)
.collect(toCollection(LinkedHashSet::new));
// You could also collect to something else
// with another collector like this:
// .collect(toList());
这里假设有以下导入:
import static java.util.stream.Collectors.toCollection;
发布于 2016-06-03 03:12:41
在Java 8中,您可以执行以下操作
mySet.stream()
.skip(start) // the offset
.limit(count) // how many items you want
.collect(Collectors.toSet());
https://stackoverflow.com/questions/12962193
复制相似问题