Pau*_*lor 29 java set subset linkedhashset
我有一个 LinkedHashSet,即一个有序集.我正在尝试找到一个函数来返回集合的子集,即集合的前20个元素.我知道我可以通过创建一个新的集合,然后使用第一集的迭代填充,但我希望更简洁的东西.
还看了一下Google的Guava库,但看不到我想要的东西.
Tom*_*icz 37
在番石榴:
Set<Integer> subset = ImmutableSet.copyOf(Iterables.limit(set, 20));
Run Code Online (Sandbox Code Playgroud)
请注意,这Iterables.limit()是懒惰评估的,因此只创建一个额外的集合.
Rei*_*eus 18
你可以这样做:
Set<Integer> set = new LinkedHashSet<>();
for (int i = 0; i < 50; i++) {
set.add(i);
}
List<Integer> list = new ArrayList<>(set);
Set<Integer> subSet = new LinkedHashSet<>(list.subList(0, 20));
Run Code Online (Sandbox Code Playgroud)
Lii*_*Lii 17
使用Java 8中的流和收集器的解决方案:
Set<Integer> subSet = set.stream()
.limit(20)
.collect(toCollection(LinkedHashSet::new));
// You could also collect to something else
// with another collector like this:
// .collect(toList());
Run Code Online (Sandbox Code Playgroud)
这假定以下导入:
import static java.util.stream.Collectors.toCollection;
Run Code Online (Sandbox Code Playgroud)
thi*_*goh 16
在Java 8中你可以做到
mySet.stream()
.skip(start) // the offset
.limit(count) // how many items you want
.collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)