Example usage for java.util List subList

List of usage examples for java.util List subList

Introduction

In this page you can find the example usage for java.util List subList.

Prototype

List<E> subList(int fromIndex, int toIndex);

Source Link

Document

Returns a view of the portion of this list between the specified fromIndex , inclusive, and toIndex , exclusive.

Usage

From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClientTest.java

private static CloseableHttpClient recordHttpClientForMultipleJsonAndStatusCodeResponse(
        List<String> jsonResponses, List<Integer> statusCodes) throws IOException {
    CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class);

    List<HttpEntity> httpEntities = jsonResponses.stream()
            .map(ConfluenceRestClientTest::recordHttpEntityForContent).collect(toList());
    when(httpResponseMock.getEntity()).thenReturn(httpEntities.get(0),
            httpEntities.subList(1, httpEntities.size()).toArray(new HttpEntity[httpEntities.size() - 1]));

    List<StatusLine> statusLines = statusCodes.stream().map(ConfluenceRestClientTest::recordStatusLine)
            .collect(toList());//w  w w .j av  a2 s  .  c o m
    when(httpResponseMock.getStatusLine()).thenReturn(statusLines.get(0),
            statusLines.subList(1, statusLines.size()).toArray(new StatusLine[statusLines.size() - 1]));

    CloseableHttpClient httpClientMock = anyCloseableHttpClient();
    when(httpClientMock.execute(any(HttpPost.class), any(HttpContext.class))).thenReturn(httpResponseMock);

    return httpClientMock;
}

From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java

/**
 * Merges a list of files into a single one by appending the contents of each file. If
 * {@code headerLines} is greater than zero, the header from the first file is written to the
 * destination file. The same number of lines is skipped in all other file, i. e. all files are
 * expected to have the same header./*from  w  w w.  java 2  s  .  c om*/
 *
 * @param sourceFiles
 *       the list of source files
 * @param destFile
 *       the destination file
 * @param headerLines
 *       the number of header lines
 * @param charset
 *       the character set to use
 */
public static void merge(final File sourceDir, final List<PerfAlyzerFile> sourceFiles, final File destFile,
        final int headerLines, final Charset charset) throws IOException {
    Files.createParentDirs(destFile);

    // simply copy the first file
    copyFile(new File(sourceDir, get(sourceFiles, 0).getFile().getPath()), destFile);

    if (sourceFiles.size() > 1) {
        // append all other files skipping headers
        try (Writer w = Files.newWriter(destFile, charset)) {
            for (PerfAlyzerFile paf : sourceFiles.subList(1, sourceFiles.size())) {
                try (BufferedReader br = Files.newReader(new File(sourceDir, paf.getFile().getPath()),
                        charset)) {

                    // skip headers
                    for (int i = 0; i < headerLines; ++i) {
                        br.readLine();
                    }

                    // copy the rest
                    CharStreams.copy(br, w);
                }
            }
        }
    }
}

From source file:com.brighttag.trident.kairos.KairosState.java

private static Map<List<Date>, QueryBuilder> groupQueriesByTimeRange(List<List<Object>> keys) {
    Map<List<Date>, QueryBuilder> queryMap = Maps.newHashMap();
    for (List<Object> key : keys) {
        Date start = toDate(key.get(0));
        Date end = toDate(key.get(1), true);
        List<Date> timeRange = ImmutableList.of(start, end);
        QueryBuilder builder = queryMap.get(timeRange);
        if (builder == null) {
            builder = QueryBuilder.getInstance().setStart(start).setEnd(end);
            queryMap.put(timeRange, builder);
        }//from w  w w  . jav a  2s. c o m
        builder.addMetric(key.get(2).toString()).addTags(toTags(key.subList(3, key.size())));
    }
    return queryMap;
}

From source file:se.uu.it.cs.recsys.ruleminer.datastructure.builder.FPTreeBuilder.java

private static void insertTransData(List<HeaderTableItem> theHeaderTable, FPTreeNode rootNode,
        List<Integer> orderedTransItemIds) {

    if (orderedTransItemIds.isEmpty()) {
        LOGGER.debug("Empty transaction items set!");
        return;//from  w w w.j a  va2  s .c o  m
    }

    Integer transHeadItemId = orderedTransItemIds.get(0);

    for (FPTreeNode node : rootNode.getChildren()) {
        if (node.getItem().getId().equals(transHeadItemId)) {
            // same item node exist as root node's child
            node.getItem().increaseCountBy(1);

            if (orderedTransItemIds.size() > 1) {
                insertTransData(theHeaderTable, node,
                        orderedTransItemIds.subList(1, orderedTransItemIds.size()));
            }

            return;
        }
    }

    // node with same id may exist, but it's not root's child
    FPTreeNode newNode = new FPTreeNode(new Item(transHeadItemId, 1));
    newNode.setForwardSameItemNode(null);
    newNode.setParent(rootNode);
    rootNode.getChildren().add(newNode);

    HeaderTableItem headerItem = HeaderTableUtil.getTableItemByItemId(theHeaderTable, transHeadItemId);

    if (headerItem == null) {
        LOGGER.debug("item: {} does not meet minSupport requirement, trans {} is discarded.", transHeadItemId,
                orderedTransItemIds);
        return;
    }

    if (headerItem.getNodeLinkHead() == null) {
        headerItem.setNodeLinkHead(newNode);
    } else {
        FPTreeNode sameItemNode = headerItem.getNodeLinkHead();

        while (sameItemNode.getForwardSameItemNode() != null) {
            sameItemNode = sameItemNode.getForwardSameItemNode();
        }

        sameItemNode.setForwardSameItemNode(newNode);
        newNode.setBackwardSameItemNode(sameItemNode);
    }

    if (orderedTransItemIds.size() > 1) {
        insertTransData(theHeaderTable, newNode, orderedTransItemIds.subList(1, orderedTransItemIds.size()));
    }
}

From source file:io.github.karols.hocr4j.Word.java

/**
 * If <code>string</code> is made from concatenating
 * several consecutive words from the <code>wordList</code>,
 * returns union of bounds of those words.
 * If not, returns <code>null</code>.
 * Spaces are ignored. Uses normal, strict string equality.
 *
 * @param wordList list of words// w w  w  .j  a  v  a  2  s.  c om
 * @param string   string to search for
 * @return bounds of the matching words
 * @see Line#findBoundsOfWord(String)
 */
@Nullable
public static Bounds findBoundsOfWord(@Nonnull List<Word> wordList, @Nonnull String string) {
    string = string.replace(" ", "");
    for (int i = wordList.size() - 1; i >= 0; i--) {
        String tillTheEndOfLine = getSpaceLessStringFromWords(wordList, i, wordList.size());
        if (tillTheEndOfLine.startsWith(string)) {
            for (int length = 1; length < wordList.size(); length++) {
                String fromFoundLocation = getSpaceLessStringFromWords(wordList, i, length);
                if (string.equals(fromFoundLocation)) {
                    return Bounds.ofAll(wordList.subList(i, i + length));
                }
            }
        }
    }
    return null; // TODO?
}

From source file:com.stratio.deep.cassandra.util.CassandraUtils.java

public static <W> void doCql3SaveToCassandra(RDD<W> rdd, ICassandraDeepJobConfig<W> writeConfig,
        Function1<W, Tuple2<Cells, Cells>> transformer) {
    if (!writeConfig.getIsWriteConfig()) {
        throw new IllegalArgumentException("Provided configuration object is not suitable for writing");
    }/*from www.  j a v a2  s .co m*/
    Tuple2<Map<String, ByteBuffer>, Map<String, ByteBuffer>> tuple = new Tuple2<>(null, null);

    RDD<Tuple2<Cells, Cells>> mappedRDD = rdd.map(transformer,
            ClassTag$.MODULE$.<Tuple2<Cells, Cells>>apply(tuple.getClass()));

    ((CassandraDeepJobConfig) writeConfig).createOutputTableIfNeeded(mappedRDD.first());

    final int pageSize = writeConfig.getBatchSize();
    int offset = 0;

    List<Tuple2<Cells, Cells>> elements = Arrays.asList((Tuple2<Cells, Cells>[]) mappedRDD.collect());
    List<Tuple2<Cells, Cells>> split;
    do {
        split = elements.subList(pageSize * (offset++), Math.min(pageSize * offset, elements.size()));

        Batch batch = QueryBuilder.batch();

        for (Tuple2<Cells, Cells> t : split) {
            Tuple2<String[], Object[]> bindVars = Utils.prepareTuple4CqlDriver(t);

            Insert insert = QueryBuilder
                    .insertInto(quote(writeConfig.getKeyspace()), quote(writeConfig.getTable()))
                    .values(bindVars._1(), bindVars._2());

            batch.add(insert);
        }
        writeConfig.getSession().execute(batch);

    } while (!split.isEmpty() && split.size() == pageSize);
}

From source file:com.twitter.aurora.scheduler.configuration.Resources.java

/**
 * Attempts to grab {@code numPorts} from the given resource {@code offer}.
 *
 * @param offer The offer to grab ports from.
 * @param numPorts The number of ports to grab.
 * @return The set of ports grabbed.//ww  w.ja v  a  2  s.  c o  m
 * @throws InsufficientResourcesException if not enough ports were available.
 */
public static Set<Integer> getPorts(Offer offer, int numPorts) throws InsufficientResourcesException {

    checkNotNull(offer);

    if (numPorts == 0) {
        return ImmutableSet.of();
    }

    List<Integer> availablePorts = Lists.newArrayList(Sets.newHashSet(
            Iterables.concat(Iterables.transform(getPortRanges(offer.getResourcesList()), RANGE_TO_MEMBERS))));

    if (availablePorts.size() < numPorts) {
        throw new InsufficientResourcesException(
                String.format("Could not get %d ports from %s", numPorts, offer));
    }

    Collections.shuffle(availablePorts);
    return ImmutableSet.copyOf(availablePorts.subList(0, numPorts));
}

From source file:com.ben12.openhab.model.util.BeanCopy.java

public static <T> void copy(final List<T> source, final List<T> destination,
        final Function<T, String> idGetter) {
    for (int i = 0; i < source.size(); i++) {
        final T newWidget = source.get(i);

        boolean found = false;
        int j = i;

        while (j < destination.size()
                && !(found = Objects.equals(idGetter.apply(newWidget), idGetter.apply(destination.get(j))))) {
            j++;//  w  w w.j a  v  a2s . com
        }

        if (found) {
            BeanCopy.copy(newWidget, destination.get(j));
            if (i != j) {
                destination.add(i, destination.remove(j));
            }
        } else {
            destination.add(i, newWidget);
        }
    }

    if (destination.size() > source.size()) {
        destination.subList(source.size(), destination.size()).clear();
    }
}

From source file:com.github.rolecraftdev.command.CommandHelper.java

/**
 * Get a sublist of a specific page within the given list using a
 * {@link ChatSection} as page number. Note that this also sends the
 * {@link CommandSender} a message when this somehow fails.
 *
 * @param sender the sender of the {@link ChatSection}
 * @param list the {@link List} to acquire a page of elements from
 * @param pageArg the page number/*from  w w  w . j a v  a  2 s .  c  o m*/
 * @param elementsPerPage the amount of elements per page
 * @param <T> the type of the given {@link List}
 * @return a bunch of elements from the given {@link List} that has been
 *         constructed by using the other given parameter values
 * @since 0.0.5
 */
public static <T> List<T> getPageFromArgs(final CommandSender sender, final List<T> list,
        final ChatSection pageArg, final int elementsPerPage) {
    final int amount = list.size();
    final int pages = (int) Math.ceil(amount / elementsPerPage);

    int page = 1;
    if (pageArg != null) {
        if (pageArg.isInt()) {
            page = pageArg.asInt();
        } else {
            sender.sendMessage(ChatColor.DARK_RED + "Invalid page!");
            return null;
        }

        if (page > pages || page < 1) {
            sender.sendMessage(ChatColor.DARK_RED + "That page doesn't exist (there are " + pages + " pages)!");
            return null;
        }
    }

    return list.subList(elementsPerPage * (page - 1), list.size() - 1);
}

From source file:com.romeikat.datamessie.core.base.util.CollectionUtil.java

public static <T> List<List<T>> splitIntoSubListsBySize(final List<T> list, final int sizeOfSublists) {
    final List<List<T>> subLists = new ArrayList<List<T>>();
    // Only one sublist
    if (sizeOfSublists < 1) {
        subLists.add(list);/*from   ww  w  . j  a va 2  s.  c o m*/
        return subLists;
    }
    // Divide
    for (int i = 0;; i++) {
        final int fromIndex = i * sizeOfSublists;
        int toIndex = (i + 1) * sizeOfSublists;
        final boolean lastSublist = list.size() <= toIndex;
        if (lastSublist) {
            toIndex = list.size();
        }
        final List<T> subList = new ArrayList<T>(list.subList(fromIndex, toIndex));
        subLists.add(subList);
        // No more sublists to go
        if (lastSublist) {
            break;
        }
    }
    // Done
    return subLists;
}