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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With