Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating subset of a Set in Java

I have a LinkedHashSet, i.e an ordered set. I'm trying to find a function to just return a subset of the set, i.e the first 20 elements of the set. I know I can do it by creating a new set and then populating using an iteration of the first set but I was hoping for something more succinct.

Also took a look at Google's Guava libraries, but couldn't see what I wanted.

like image 881
Paul Taylor Avatar asked Oct 18 '12 19:10

Paul Taylor


People also ask

How do you create a subset of a Set in Java?

The subSet() method of SortedSet interface in Java is used to return a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. The set returned by this method is backed by this set, so changes in the returned set are reflected in this set, and vice-versa.

How do you create a subset of a Set?

Set A is said to be a subset of Set B if all the elements of Set A are also present in Set B. In other words, set A is contained inside Set B. Example: If set A has {X, Y} and set B has {X, Y, Z}, then A is the subset of B because elements of A are also present in set B.

How do you make a subset from TreeSet?

TreeSet. subSet() is used to return a subset of the existing TreeSet within a range mentioned in the parameter. The method takes in an upper limit and a lower limit and returns all the elements mentioned in the range. The lower limit is included if the element is present within the set and the upper limit is excluded.

How do you find the subset of a Set of numbers in Java?

You can find all subsets of set or power set using iteration as well. There will be 2^N subsets for a given set, where N is the number of elements in set. For example, there will be 2^4 = 16 subsets for the set {1, 2, 3, 4}. Each '1' in the binary representation indicate an element in that position.


1 Answers

In Guava:

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

Note that Iterables.limit() is evaluated lazily, so only one extra collection is created.

like image 51
Tomasz Nurkiewicz Avatar answered Oct 04 '22 16:10

Tomasz Nurkiewicz