I have a set
我有一套
Set<Long> entityIds;
I want to divide it into packs of 10 pieces. To end up with a sheet of sets and in each set of 10 elements, like this:
我想把它分成10件装。最终得到一组集合,每组10个元素,如下所示:
List<Set<Long>> batches
How can I do it?
我该怎么做?
My Solution:
private List<Set<T>> splitSet(Set<T> input) {
List<Set<T>> batches = new ArrayList<>();
for (int p = 0; p <= input.size(); p += 10) {
Set<T> partSet = input.stream().skip(p).limit(10).collect(Collectors.toSet());
batches.add(partSet);
}
return batches;
}
2 个解决方案
#1
2
You can use the queue or stack and just pop/pull elements
您可以使用队列或堆栈,只需弹出/拉动元素
private static <T> List<Set<T>> extract(Set<T> set, int size){
List<Set<T>> result = new ArrayList<>();
Queue<T> queue = new LinkedList<>(set);
while (!queue.isEmpty() && size > 0){
Set<T> subSet = new HashSet<>();
while (subSet.size() < size && !queue.isEmpty()){
subSet.add(queue.poll());
}
result.add(subSet);
}
return result;
}
#2
1
I'd probably do it something like this:
我可能会这样做:
static <T> List<Set<T>> splitSet(Set<T> set, int n) {
List<Set<T>> split = new ArrayList<>();
int count = 0;
Set<T> newSet = new HashSet<>();
for (T id : set) {
if (++count % n == 0) {
split.add(newSet);
newSet = new HashSet<>();
}
newSet.add(id);
}
if (!newSet.isEmpty()) {
split.add(newSet);
}
return split;
}
public void test(String[] args) throws Exception {
Set<Long> ids = new HashSet<>();
for (long i = 0; i < 98; i++) {
ids.add(i);
}
System.out.println(splitSet(ids, 10));
}
#1
2
You can use the queue or stack and just pop/pull elements
您可以使用队列或堆栈,只需弹出/拉动元素
private static <T> List<Set<T>> extract(Set<T> set, int size){
List<Set<T>> result = new ArrayList<>();
Queue<T> queue = new LinkedList<>(set);
while (!queue.isEmpty() && size > 0){
Set<T> subSet = new HashSet<>();
while (subSet.size() < size && !queue.isEmpty()){
subSet.add(queue.poll());
}
result.add(subSet);
}
return result;
}
#2
1
I'd probably do it something like this:
我可能会这样做:
static <T> List<Set<T>> splitSet(Set<T> set, int n) {
List<Set<T>> split = new ArrayList<>();
int count = 0;
Set<T> newSet = new HashSet<>();
for (T id : set) {
if (++count % n == 0) {
split.add(newSet);
newSet = new HashSet<>();
}
newSet.add(id);
}
if (!newSet.isEmpty()) {
split.add(newSet);
}
return split;
}
public void test(String[] args) throws Exception {
Set<Long> ids = new HashSet<>();
for (long i = 0; i < 98; i++) {
ids.add(i);
}
System.out.println(splitSet(ids, 10));
}