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:org.fenixedu.cms.domain.component.PostsPresentationBean.java

public HashMap<String, Object> paginate(Page page, int currentPage, int postsPerPage) {

    List<List<Wrap>> pages = Lists.partition(getVisiblePosts(), postsPerPage);
    currentPage = ensureRange(currentPage, FIRST_PAGE_INDEX, pages.size());
    List<Wrap> currentPagePosts = pages.isEmpty() ? Lists.newArrayList()
            : pages.get(currentPage - FIRST_PAGE_INDEX);

    HashMap<String, Object> pagination = Maps.newHashMap();
    pagination.put("pages", createPagesList(pages.size()));
    pagination.put("current", currentPage);
    pagination.put("posts", currentPagePosts);
    return pagination;
}

From source file:org.kuali.rice.kim.impl.identity.IdentityServiceDaoJpa.java

@Override
public Map<String, EntityNamePrincipalName> getDefaultNamesByPrincipalIds(List<String> principalIds) {
    Map<String, EntityNamePrincipalName> results = new HashMap<String, EntityNamePrincipalName>();

    // This partitioning is required because EclipseLink does not handle splitting up IN clauses with a large number of values into chunks
    List<List<String>> partitionedPrincipalIds = Lists.partition(principalIds, PARTITION_SIZE);
    for (List<String> partition : partitionedPrincipalIds) {
        List<NameHolder> names = getEntityManager()
                .createNamedQuery("EntityNameBo.findDefaultNamesForPrincipalIds", NameHolder.class)
                .setParameter("principalIds", partition).getResultList();
        for (NameHolder name : names) {
            EntityNamePrincipalName.Builder nameBuilder = EntityNamePrincipalName.Builder.create();
            EntityNameBo entityName = name.getEntityName();
            entityName.setSuppressName(name.isSuppressName());
            nameBuilder.setDefaultName(EntityName.Builder.create(entityName));
            nameBuilder.setPrincipalName(name.getPrincipalName());
            results.put(name.getPrincipalId(), nameBuilder.build());
        }/*ww w  . j a  v a 2 s  .  c o m*/
    }
    return results;
}

From source file:org.apache.geode.geospatial.function.ClearRegion.java

@Override
public void execute(FunctionContext context) {

    String regionName = ((String[]) context.getArguments())[0];
    Region region = CacheFactory.getAnyInstance().getRegion(regionName);

    if (PartitionRegionHelper.isPartitionedRegion(region)) {
        region = PartitionRegionHelper.getLocalPrimaryData(region);
    }//  w ww.j a va2 s  . co  m
    int size = region.size();
    final Region lambdaRegion = region;
    Collection<Collection> partitionedKeys = Lists.partition(new ArrayList(region.keySet()), 1000);
    partitionedKeys.forEach(keySet -> lambdaRegion.removeAll(keySet));
    context.getResultSender().lastResult("Removed " + size + " keys.");
}

From source file:com.watchrabbit.crawler.batch.service.TaskScheduler.java

@Scheduled(fixedDelayString = "${crawler.batch.delay:10000}")
public void execute() {
    try {/*ww  w  .j a v a2s  . c  o m*/
        LOGGER.info("Starting address job");

        List<String> queue = dispatcherServiceFacade.getQueue(maxQueueProcessingSize);
        if (queue.size() > 0) {
            List<List<String>> partition = Lists.partition(queue,
                    queue.size() / dispatcherServiceFacade.getInstanceCount());
            partition.forEach(dispatcherServiceFacade::dispatch);
        }
    } catch (RuntimeException e) {
        LOGGER.error("Address job exception", e);
    }
}

From source file:io.github.mywarp.mywarp.platform.paginatedcontent.SimplePaginatedContent.java

private SimplePaginatedContent(String heading, String note, int numPerPage, List<Message> toDisplay) {
    this.heading = heading;
    this.note = note;
    this.pages = Lists.partition(toDisplay, showPerPage(numPerPage));
}

From source file:matching.edmonds2.Matching.java

@Override
public <T> matching.Matches<T> from(final UndirectedGraph<T> residualGraph) {

    final ShortestPathInterface<T> routingInterface = residualGraph.fetch(ShortestPathFeature.class).up();
    final double[][] weights = routingInterface.getShortestPathWeights();

    final WeightedMatchDouble weightedMatch = new WeightedMatchDouble(weights);
    final int[] mate = weightedMatch.weightedMatch(WeightedMatchDouble.MINIMIZE);
    final int[] matched = weightedMatch.getMatched(mate);

    double cost = 0.0;
    final List<List<Integer>> partition = Lists.partition(Ints.asList(matched), 2);
    final Map<T, T> matches = Maps.newHashMap();

    for (final List<Integer> position : partition) {
        final Integer i = position.get(0);
        final Integer j = position.get(1);
        matches.put(residualGraph.get(i), residualGraph.get(j));
        cost += weights[i][j];/*from   w w  w.  ja  va2  s.  c  o  m*/
    }

    return new matching.Matches<T>(matches, cost);
}

From source file:com.amazonservices.mws.products.samples.GetMyPriceForSKUSample.java

/**
 *  Command line entry point.//from   w ww .ja  v  a  2 s.  c  o  m
 * @throws IOException 
 * @throws InterruptedException 
 */
public static void main(String[] args) throws IOException, InterruptedException {

    //retrieve SKU from DB

    //open db connection to retireve skus.

    String url = "0";
    String username = "0";
    String password = "0";

    System.out.println("Loading driver...");
    try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver loaded!");
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Cannot find the driver in the classpath!", e);
    }

    System.out.println("Connecting database...");

    try (Connection connection = DriverManager.getConnection(url, username, password)) {

        System.out.println("Database connected!");

        //if successfully connected, will begin to retrieve sku #

        String query = "select SKU from AmazonListing";

        Statement st = connection.createStatement();

        //Intialize Arraylist to store sku;
        ArrayList<String> str = new ArrayList<String>();

        // execute the preparedstatement, and get result
        ResultSet rs = st.executeQuery(query);

        //use object attribute to store result, then store object attributes to a list

        AmazonListing al = new AmazonListing(query, query, query, query, query, query, query, query, query,
                query, query, query, query, query, query, query, query, query, query, query, query, query);

        //while there is sku in result, stored it in object, then add object to arraylist

        while (rs.next()) {

            //set retrieved ordernumbers from resultset rs to al object
            al.setSku(rs.getString("SKU"));

            //write  al object to arraylist of string str
            str.add(al.getSku());

        }

        //test and try 

        for (int i = 0; i < str.size(); i++) {

            System.out.println(str.get(i));

        }

        //after retrieving the result, close the connection
        connection.close();

        // Get a client connection.
        // Make sure you've set the variables in MarketplaceWebServiceProductsSampleConfig.
        MarketplaceWebServiceProductsClient client = MarketplaceWebServiceProductsSampleConfig.getClient();

        // Create a request.
        GetMyPriceForSKURequest request = new GetMyPriceForSKURequest();
        String sellerId = "0";
        request.setSellerId(sellerId);
        String mwsAuthToken = "0";
        request.setMWSAuthToken(mwsAuthToken);
        String marketplaceId = "0";
        request.setMarketplaceId(marketplaceId);

        //initialize for request input
        SellerSKUListType listofskus = new SellerSKUListType();

        //only accept 20 sku  at a time, this code is to send 20 at a time.  Lists.partition is google lang
        for (List<String> skupartition : Lists.partition(str, 20)) {

            System.out.println(skupartition.size());

            //set a list of size 50 to request
            listofskus.setSellerSKU(skupartition);

            //set request
            request.setSellerSKUList(listofskus);

            // Make the call.
            GetMyPriceForSKUSample.invokeGetMyPriceForSKU(client, request);

            System.out.println("Im about to get another set");

            //time paused for each request, time out in mili seconds. 
            Thread.sleep(10000);

        }

    } catch (SQLException e) {
        throw new IllegalStateException("Cannot connect the database!", e);
    }

}

From source file:com.pinterest.pinlater.backends.common.PinLaterBackendUtils.java

/**
 * Executes a batch of requests asynchronously in a partitioned manner,
 * with the specified parallelism.//from   ww w . java2  s  .c o  m
 *
 * @param requests      List of requests to execute.
 * @param parallelism   Desired parallelism (must be > 0).
 * @param executeBatch  Function to execute each partitioned batch of requests.
 * @param <Req>         Request type.
 * @param <Resp>        Response type.
 * @return List of response futures.
 */
public static <Req, Resp> List<Future<Resp>> executePartitioned(List<Req> requests, int parallelism,
        Function<List<Req>, Future<Resp>> executeBatch) {
    MorePreconditions.checkNotBlank(requests);
    Preconditions.checkArgument(parallelism > 0);
    Preconditions.checkNotNull(executeBatch);

    int sizePerPartition = Math.max(requests.size() / parallelism, 1);
    List<List<Req>> partitions = Lists.partition(requests, sizePerPartition);
    List<Future<Resp>> futures = Lists.newArrayListWithCapacity(partitions.size());
    for (final List<Req> request : partitions) {
        futures.add(executeBatch.apply(request));
    }
    return futures;
}

From source file:com.dianping.apistatic.Job.MovieShowBlockListCrawlerJob.java

@Override
protected void execute() throws Exception {
    movieShowIds.clear();//from  ww w . ja  v a  2 s.  co m
    shopIdMap = readMapFromFile(Constants.SHOPIDMAP_PATH); // key cityid
    movieIdMap = readMapFromFile(Constants.MOVIEIDMAP_PATH); // key cityid

    if (MapUtils.isEmpty(shopIdMap) || MapUtils.isEmpty(movieIdMap)) {
        log("shopIdMapmovieIdMap", new RuntimeException("shopIdMapmovieIdMap"));
        return;
    }

    List<Integer> cityIds = getCityIds();
    if (CollectionUtils.isEmpty(cityIds)) {
        return;
    }

    int partitionSize = (cityIds.size() > 4 ? cityIds.size() / 4 : cityIds.size());
    List<List<Integer>> cityIdsList = Lists.partition(cityIds, partitionSize);
    CountDownLatch countDownLatch = new CountDownLatch(cityIdsList.size());

    for (List<Integer> list : cityIdsList) {
        MovieShowBlockCrawlerThread thread = new MovieShowBlockCrawlerThread(list, countDownLatch);
        thread.start();
    }

    try {
        countDownLatch.await();
    } catch (Exception e) {
        log("countDownLatch ", e);
        return;
    }

    if (CollectionUtils.isNotEmpty(movieShowIds)) {
        writeObjectAsJsonToFile(Constants.MOVIESHOWIDS_PATH, movieShowIds);
    }
}

From source file:tradetools.dataloader.service.impl.yahoofinance.YahooFinanceStockLoaderServiceImpl.java

@Override
public List<Stock> loadStocksBySymbolIn(List<String> symbols) {
    List<List<String>> pages = Lists.partition(symbols, 50);
    for (List<String> page : pages) {

    }/*from  w w w. ja v  a 2s.  c o m*/
    // TODO Auto-generated method stub
    return null;
}