Creating subset of a Set in Java
Solution 1
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.
Solution 2
In Java 8 you can do
mySet.stream()
.skip(start) // the offset
.limit(count) // how many items you want
.collect(Collectors.toSet());
Solution 3
A solution using streams and collectors:
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());
This assumes the following import:
import static java.util.stream.Collectors.toCollection;
Solution 4
You could do this:
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));
Solution 5
You can either use at first a SortedSet
as the subSet
method exists on it.
You can also add the content of your set to a List
and use the subList
method on it. But it depends on the amount of data stored in your Set
as you would not want to duplicate an enormous volume of data.
Otherwise you should stay with the iteration over the Set as it will be more efficient.
Paul Taylor
Runs Albunack providing awesome artist discographies and the Jaikoz and SongKong Music Tagger applications. Main skills:Java and Databases. Also, photographer concentrating on the less obvious in South-West England, photographs can be seen at Secret Dorset Photo
Updated on May 11, 2021Comments
-
Paul Taylor about 3 years
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.
-
Paul Taylor over 11 yearsTHanks that look neat, except for the fact you have to create both another Set and an ArrayList but I can live with that.
-
Paul Taylor over 11 yearsThanks I had an inkling there would be a way to do this in guava.
-
Dejell over 9 yearswhat if I want get from index 20-40?
-
dtrunk over 8 yearsTo avoid a
IndexOutOfBoundsException
useMath.min(list.size(), 20)
as 2nd parameter ofsubList
in case of a dynamically filled list. -
dnellis74 over 7 yearsYou mean limit() not skip() I think.
-
Farid over 2 years@Dejell As you have already figured out by now, there is no index in
Set
unless its implementation has one e.g.SortedSet