35

我有一个 LinkedHashSet,即一个有序集。我试图找到一个函数来返回集合的一个子集,即集合的前 20 个元素。我知道我可以通过创建一个新集合然后使用第一个集合的迭代进行填充来做到这一点,但我希望有更简洁的东西。

还看了谷歌的番石榴库,但看不到我想要的。

4

6 回答 6

40

在番石榴中:

Set<Integer> subset = ImmutableSet.copyOf(Iterables.limit(set, 20));

请注意,这Iterables.limit()是延迟评估的,因此只创建了一个额外的集合。

于 2012-10-18T19:36:22.253 回答
23

使用流和收集器的解决方案:

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;
于 2015-11-16T14:41:52.853 回答
23

在 Java 8 中你可以做

mySet.stream()
   .skip(start) // the offset
   .limit(count) // how many items you want
   .collect(Collectors.toSet());
于 2016-06-02T19:12:41.003 回答
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));
于 2012-10-18T19:30:55.527 回答
5

您可以先使用 a SortedSet,因为该subSet方法存在于其上。

您还可以将集合的内容添加到 aList并在其上使用subList方法。但这取决于您存储的数据量,Set因为您不想复制大量数据。

否则,您应该继续对 Set 进行迭代,因为它会更有效。

于 2012-10-18T19:30:49.017 回答
2

简单的辅助方法(您可以将它用于 Set 或任何其他集合):

public static <T> List<T> listOf(final Collection<T> set, final int limit) {
    final List<T> list = new ArrayList<>(limit);

    final Iterator<T> i = set.iterator();
    for (int j = 0; j < limit && i.hasNext(); j++) {
        list.add(i.next());
    }

    return list;
}
于 2015-02-26T05:21:33.653 回答