Example usage for com.google.common.collect Lists partition

List of usage examples for com.google.common.collect Lists partition

Introduction

In this page you can find the example usage for com.google.common.collect Lists partition.

Prototype

public static <T> List<List<T>> partition(List<T> list, int size) 

Source Link

Document

Returns consecutive List#subList(int,int) sublists of a list, each of the same size (the final list may be smaller).

Usage

From source file:com.davidbracewell.ml.utils.DataSets.java

/**
 * Create folds./*ww  w . ja  v a2s.  co  m*/
 *
 * @param data     the data
 * @param numFolds the num folds
 * @return the list
 */
public static <V> List<List<V>> nFolds(List<V> data, int numFolds) {
    Preconditions.checkNotNull(data);
    Preconditions.checkArgument(numFolds > 1, "Must be at least two folds.");
    Preconditions.checkArgument(data.size() >= numFolds,
            "Must be at least number of fold items in the data set.");
    return Lists.partition(data, (int) Math.floor((double) data.size() / numFolds));
}

From source file:edu.anu.spice.Annotator.java

public void setInput(List<String> captions) {
    this.batches = Lists.partition(captions, this.maxBatchSize);
    this.batchNum = 0;
}

From source file:org.sonar.gherkin.checks.RuleDescriptionsGenerator.java

private String generateForbiddenWordsHtmlTable() {
    StringBuilder html = new StringBuilder("<table style=\"border: 0;\">\n");
    List<List<String>> subLists = Lists.partition(
            Arrays.stream(WordingBusinessLevelCheck.FORBIDDEN_WORDS).sorted().collect(Collectors.toList()), 3);
    for (List<String> subList : subLists) {
        html.append("<tr>");
        for (String word : subList) {
            html.append("<td style=\"border: 0; \">");
            html.append(word);/* ww w.j a  v  a 2s .c  o  m*/
            html.append("</td>\n");
        }
        html.append("</tr>");
    }
    html.append("</table>\n");
    return html.toString();
}

From source file:de.cosmocode.palava.workqueue.BatchWorkQueue.java

@Override
public void run() {

    final List<E> all = Lists.newArrayList();

    while (true) {
        final E e = queue.poll();
        if (e == null)
            break;
        all.add(e);/*from   ww  w  .  ja va  2 s  . co m*/
    }

    switch (batchSize) {
    case 0: {
        processor.apply(all);
        break;
    }
    case 1: {
        for (E e : all) {
            processor.apply(Collections.singletonList(e));
        }
        break;
    }
    default: {
        for (List<E> partition : Lists.partition(all, batchSize)) {
            processor.apply(partition);
        }
        break;
    }
    }
}

From source file:com.spotify.helios.rollingupdate.RollingUndeployPlanner.java

@Override
public List<RolloutTask> plan(final Map<String, HostStatus> hostsAndStatuses) {
    // we only care about hosts that are UP
    final List<String> hosts = hostsAndStatuses.entrySet().stream()
            .filter(entry -> entry.getValue().getStatus().equals(HostStatus.Status.UP))
            .map(entry -> entry.getKey()).collect(Collectors.toList());

    // generate the rollout tasks
    final List<RolloutTask> rolloutTasks = Lists.newArrayList();
    final int parallelism = deploymentGroup.getRolloutOptions() != null
            ? deploymentGroup.getRolloutOptions().getParallelism()
            : 1;/*w w w .  jav a2 s. com*/

    Lists.partition(hosts, parallelism).forEach(partition -> rolloutTasks.addAll(rolloutTasks(partition)));

    return ImmutableList.copyOf(rolloutTasks);
}

From source file:org.sonar.json.checks.RuleDescriptionsGenerator.java

private String generateHtmlTable(List<String> elements) {
    StringBuilder html = new StringBuilder("<table style=\"border: 0;\">");
    List<List<String>> subLists = Lists.partition(elements, 3);
    for (List<String> subList : subLists) {
        html.append("<tr>");
        for (String element : subList) {
            html.append("<td style=\"border: 0;\">").append(element).append("</td>");
        }//from   w ww . j a v a  2 s .  co  m
        html.append("</tr>");
    }
    html.append("</table>");
    return html.toString();
}

From source file:org.asoem.greyfish.utils.concurrent.RecursiveActions.java

/**
 * Creates a {@code RecursiveAction} which applies a function {@code f} to all elements in the given {@code list}.
 * If the size of the list exceeds the given {@code size}, then the list will be split into partitions of that
 * {@code size} and {@code f} will be applied on them in parallel.
 *
 * @param list the elements on which the function will be applied
 * @param f    the function to apply//from   w  ww.j  a  va2s . c o  m
 * @param size the desired size of each sublist (the last may be smaller)
 * @return a {@code RecursiveAction} which should be executed with a {@link ForkJoinPool}
 */
public static <T> RecursiveAction foreach(final List<T> list, final Function<? super T, Void> f,
        final int size) {
    checkNotNull(list);
    checkNotNull(f);

    if (list.isEmpty()) {
        return NULL_ACTION;
    } else {
        return new RecursiveAction() {
            @Override
            protected void compute() {
                checkState(inForkJoinPool(),
                        "This action is executed from outside of an ForkJoinPool which is forbidden");

                if (list.size() < size) {
                    applyFunction(list);
                } else {
                    invokeAll(partitionAndFork(list));
                }
            }

            private List<RecursiveAction> partitionAndFork(final List<T> list) {
                // copyOf is prevents deadlock!
                return ImmutableList.copyOf(
                        Lists.transform(Lists.partition(list, size), new Function<List<T>, RecursiveAction>() {
                            @Nullable
                            @Override
                            public RecursiveAction apply(@Nullable final List<T> input) {
                                return new RecursiveAction() {
                                    @Override
                                    protected void compute() {
                                        applyFunction(input);
                                    }
                                };
                            }
                        }));
            }

            private void applyFunction(final Iterable<T> elements) {
                for (final T element : elements) {
                    f.apply(element);
                }
            }
        };
    }
}

From source file:ro.cosu.vampires.client.allocation.FixedCpuSetAllocator.java

public FixedCpuSetAllocator(Builder builder) {
    final List<Integer> integerList = IntStream.iterate(0, i -> i + 1).boxed().limit(builder.totalCpuCount)
            .collect(Collectors.toList());

    // partitions the list of cpus in [cpusetSize] sublists
    Lists.partition(integerList, builder.cpuSetSize).stream().map(HashSet::new).map(CpuSet::new)
            .forEach(cpuList::addLast);/*from   ww w .j  a v  a 2 s  .co  m*/

    this.totalCpuCount = builder.totalCpuCount;
}

From source file:com.netflix.exhibitor.core.automanage.ClusterStatusTask.java

@Override
protected List<ServerStatus> compute() {
    List<ServerStatus> statuses = Lists.newArrayList();

    int size = specs.size();
    switch (size) {
    case 0: {// w w  w  .  j a v a  2  s .  co  m
        break; // nothing to do
    }

    case 1: {
        statuses.add(getStatus(specs.get(0)));
        break;
    }

    default: {
        List<ClusterStatusTask> tasks = Lists.newArrayList();
        for (List<ServerSpec> subList : Lists.partition(specs, size / 2)) {
            ClusterStatusTask task = new ClusterStatusTask(exhibitor, subList);
            task.fork();
            tasks.add(task);
        }

        for (ClusterStatusTask task : tasks) {
            statuses.addAll(task.join());
        }
        break;
    }
    }
    return statuses;
}

From source file:com.netflix.spinnaker.clouddriver.ecs.deploy.EcsServerGroupNameResolver.java

@Override
public List<TakenSlot> getTakenSlots(String familyName) {
    List<String> relevantServices = new ArrayList<>();
    String nextToken = null;//from ww  w.  j a v  a2 s . co  m
    do {
        ListServicesRequest request = new ListServicesRequest().withCluster(ecsClusterName);
        if (nextToken != null) {
            request.setNextToken(nextToken);
        }

        ListServicesResult result = ecs.listServices(request);
        for (String serviceArn : result.getServiceArns()) {
            if (serviceArn.contains(familyName)) {
                relevantServices.add(serviceArn);
            }
        }

        nextToken = result.getNextToken();
    } while (nextToken != null && nextToken.length() != 0);

    List<TakenSlot> slots = new ArrayList<>();
    List<List<String>> serviceBatches = Lists.partition(relevantServices, 10);
    for (List<String> serviceBatch : serviceBatches) {
        DescribeServicesRequest request = new DescribeServicesRequest().withCluster(ecsClusterName)
                .withServices(serviceBatch);
        DescribeServicesResult result = ecs.describeServices(request);
        for (Service service : result.getServices()) {
            Names names = Names.parseName(service.getServiceName());
            slots.add(new TakenSlot(service.getServiceName(), names.getSequence(), service.getCreatedAt()));
        }
    }

    return slots;
}