Example usage for com.google.common.collect Iterators size

List of usage examples for com.google.common.collect Iterators size

Introduction

In this page you can find the example usage for com.google.common.collect Iterators size.

Prototype

public static int size(Iterator<?> iterator) 

Source Link

Document

Returns the number of elements remaining in iterator .

Usage

From source file:org.eclipse.emf.compare.match.eobject.URIDistance.java

/**
 * Return a metric result URI similarities. It compares 2 lists of fragments and return an int
 * representing the level of similarity. 0 - they are exactly the same to 10 - they are completely
 * different. "adding a fragment", "removing a fragment".
 * /*from   w  w w  .j a v  a  2 s  .  c o m*/
 * @param aPath
 *            First of the two list of {@link String}s to compare.
 * @param bPath
 *            Second of the two list of {@link String}s to compare.
 * @return The number of changes to transform one uri to another one.
 */
public int proximity(Iterable<String> aPath, Iterable<String> bPath) {
    int aSize = 0;
    int bSize = 0;
    Iterator<String> itA = aPath.iterator();
    Iterator<String> itB = bPath.iterator();
    boolean areSame = true;
    int commonSegments = 0;
    int remainingASegments = 0;
    int remainingBSegments = 0;
    while (itA.hasNext() && itB.hasNext() && areSame) {
        String a = itA.next();
        String b = itB.next();
        if (a.equals(b)) {
            commonSegments++;
        } else {
            areSame = false;
        }
        aSize++;
        bSize++;

    }
    if (commonSegments == 0) {
        return MAX_DISTANCE;
    }
    remainingASegments = aSize + Iterators.size(itA) - commonSegments;
    remainingBSegments = bSize + Iterators.size(itB) - commonSegments;

    int nbSegmentsToGoFromAToB = remainingASegments + remainingBSegments;
    return (nbSegmentsToGoFromAToB * 10) / (commonSegments * 2 + nbSegmentsToGoFromAToB);
}

From source file:org.apache.kudu.util.ClientTestUtil.java

/**
 * Counts the rows in the provided scan tokens.
 *//*from   w  ww  .ja  v a2 s. co m*/
public static int countScanTokenRows(List<KuduScanToken> tokens, final String masterAddresses,
        final long operationTimeoutMs) throws IOException, InterruptedException {
    final AtomicInteger count = new AtomicInteger(0);
    List<Thread> threads = new ArrayList<>();
    for (final KuduScanToken token : tokens) {
        final byte[] serializedToken = token.serialize();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try (KuduClient contextClient = new KuduClient.KuduClientBuilder(masterAddresses)
                        .defaultAdminOperationTimeoutMs(operationTimeoutMs).build()) {
                    KuduScanner scanner = KuduScanToken.deserializeIntoScanner(serializedToken, contextClient);
                    try {
                        int localCount = 0;
                        while (scanner.hasMoreRows()) {
                            localCount += Iterators.size(scanner.nextRows());
                        }
                        count.addAndGet(localCount);
                    } finally {
                        scanner.close();
                    }
                } catch (Exception e) {
                    LOG.error("exception in parallel token scanner", e);
                }
            }
        });
        thread.run();
        threads.add(thread);
    }

    for (Thread thread : threads) {
        thread.join();
    }
    return count.get();
}

From source file:de.elatexam.editor.components.panels.tree.ComplexTaskdefTreeProvider.java

public boolean hasChildren(final Indexed object) {
    return Iterators.size(getChildren(object)) > 0;
}

From source file:com.palantir.atlasdb.keyvalue.impl.InMemoryKeyValueService.java

@Override
public Map<Cell, Value> getRows(String tableName, Iterable<byte[]> rows, ColumnSelection columnSelection,
        long timestamp) {
    Map<Cell, Value> result = Maps.newHashMap();
    ConcurrentSkipListMap<Key, byte[]> table = getTableMap(tableName).entries;

    for (byte[] row : rows) {
        Cell rowBegin = Cells.createSmallestCellForRow(row);
        Cell rowEnd = Cells.createLargestCellForRow(row);
        PeekingIterator<Entry<Key, byte[]>> entries = Iterators.peekingIterator(table
                .subMap(new Key(rowBegin, Long.MIN_VALUE), new Key(rowEnd, timestamp)).entrySet().iterator());
        while (entries.hasNext()) {
            Entry<Key, byte[]> entry = entries.peek();
            Key key = entry.getKey();
            Iterator<Entry<Key, byte[]>> cellIter = takeCell(entries, key);
            if (columnSelection.contains(key.col)) {
                Entry<Key, byte[]> lastEntry = null;
                while (cellIter.hasNext()) {
                    Entry<Key, byte[]> curEntry = cellIter.next();
                    if (curEntry.getKey().ts >= timestamp) {
                        break;
                    }// w  w w.jav  a  2  s.  co m
                    lastEntry = curEntry;
                }
                if (lastEntry != null) {
                    long ts = lastEntry.getKey().ts;
                    byte[] value = lastEntry.getValue();
                    result.put(Cell.create(row, key.col), Value.create(value, ts));
                }
            }
            Iterators.size(cellIter);
        }
    }

    return result;
}

From source file:fr.obeo.emf.specimen.SpecimenGenerator.java

private void createResource(ResourceSet resourceSet, Map<EClass, Integer> resourcesSize,
        TreeIterator<EObject> eAllContents, EObject eObject, List<EObject> ret) {
    TreeIterator<EObject> properContents = EcoreUtil.getAllProperContents(eObject, true);
    int allProperContentsSize = Iterators.size(properContents);
    EClass eClass = eObject.eClass();//from  w  w w. j a  v  a 2s  .co  m
    Integer integer = resourcesSize.get(eClass);
    if (integer != null && allProperContentsSize <= integer.intValue()) {
        createResource(resourceSet, eObject);
        setNextResourceSizeForType(resourcesSize, eClass);
        eAllContents.prune();
    } else if (eObject.eContainer() == null) {
        List<EObject> precedingSibling = ret.subList(0, ret.indexOf(eObject));
        TreeIterator<Object> allPrecedingSiblingContents = EcoreUtil.getAllProperContents(precedingSibling,
                true);
        int allPrecedingSiblingContentsSize = Iterators.size(allPrecedingSiblingContents);
        if (integer != null && allPrecedingSiblingContentsSize >= integer.intValue()) {
            createResource(resourceSet, eObject);
            setNextResourceSizeForType(resourcesSize, eClass);
            eAllContents.prune();
        }
    }
}

From source file:org.apache.james.mailrepository.lib.AbstractMailRepository.java

@Override
public long size() throws MessagingException {
    return Iterators.size(list());
}

From source file:com.eventsourcing.inmem.MemoryJournal.java

@Override
@SuppressWarnings("unchecked")
public <T extends Entity> long size(Class<T> klass) {
    if (Event.class.isAssignableFrom(klass)) {
        return Iterators.size(eventIterator((Class<Event>) klass));
    }//from w w  w.  j  av  a2s.  com
    if (Command.class.isAssignableFrom(klass)) {
        return Iterators.size(commandIterator((Class<Command<?, ?>>) klass));
    }
    return 0;
}

From source file:org.geogig.commands.pr.PRHealthCheckOp.java

static CompletableFuture<Integer> countMissingCommits(Ref oldTip, Ref newTip, Context context) {

    if (oldTip.getObjectId().equals(newTip.getObjectId())) {
        return CompletableFuture.completedFuture(Integer.valueOf(0));
    }//from w ww.  j  av a  2s  .  c  om

    return CompletableFuture.supplyAsync(() -> {
        Iterator<RevCommit> missingCommits = context.command(LogOp.class).setUntil(newTip.getObjectId())
                .setSince(oldTip.getObjectId()).call();
        int commitsBehind = Iterators.size(missingCommits);
        return commitsBehind;
    });
}

From source file:eu.opensourceprojects.mondo.benchmarks.transformationzoo.instantiator.SpecimenGenerator.java

@SuppressWarnings("unused")
private void createResource(ResourceSet resourceSet, Map<EClass, Integer> resourcesSize,
        TreeIterator<EObject> eAllContents, EObject eObject, List<EObject> ret) {
    TreeIterator<EObject> properContents = EcoreUtil.getAllProperContents(eObject, true);
    int allProperContentsSize = Iterators.size(properContents);
    EClass eClass = eObject.eClass();/*from  w  ww .j  a  va2s  . c om*/
    Integer integer = resourcesSize.get(eClass);
    if (integer != null && allProperContentsSize <= integer.intValue()) {
        createResource(resourceSet, eObject);
        setNextResourceSizeForType(resourcesSize, eClass);
        eAllContents.prune();
    } else if (eObject.eContainer() == null) {
        List<EObject> precedingSibling = ret.subList(0, ret.indexOf(eObject));
        TreeIterator<Object> allPrecedingSiblingContents = EcoreUtil.getAllProperContents(precedingSibling,
                true);
        int allPrecedingSiblingContentsSize = Iterators.size(allPrecedingSiblingContents);
        if (integer != null && allPrecedingSiblingContentsSize >= integer.intValue()) {
            createResource(resourceSet, eObject);
            setNextResourceSizeForType(resourcesSize, eClass);
            eAllContents.prune();
        }
    }
}

From source file:eu.project.ttc.engines.Contextualizer.java

@Override
public void collectionProcessComplete() throws AnalysisEngineProcessException {
    LOGGER.info("Contextualizing");
    if (termIndexResource.getTermIndex().getTerms().isEmpty())
        return;//from w ww . j  a  v a2  s  .c o m

    // 0- drop all context vectors
    LOGGER.debug("0 - Drop all context vectors");
    TermIndex termIndex = termIndexResource.getTermIndex();
    for (Term t : termIndex.getTerms())
        if (t.isContextVectorComputed())
            t.clearContext();

    // 1- index all occurrences in source documents
    LOGGER.debug("1 - Create occurrence index");
    termIndex.createOccurrenceIndex();

    int total = allTerms ? termIndex.getTerms().size() : Iterators.size(termIndex.singleWordTermIterator());
    // 2- Generate context vectors
    LOGGER.debug("2 - Create context vectors. allTerms: {} (number of contexts to compute: {})", allTerms,
            total);
    Iterator<Term> iterator = getTermIterator();
    for (Term t : IteratorUtils.toIterable(iterator))
        t.computeContextVector(coTermType, scope, this.minimumCooccFrequencyThreshold, useTermClasses);

    // 3- Normalize context vectors
    if (normalizeAssocRate) {
        LOGGER.debug("3 - Normalizing context vectors");
        LOGGER.debug("3a - Generating the cross table");
        CrossTable crossTable = new CrossTable(termIndex);
        LOGGER.debug("3b - Normalizing {} context vectors", total);
        String traceMsg = "[Progress: {} / {}] Normalizing term {}";
        int progress = 0;
        for (Term t : IteratorUtils.toIterable(getTermIterator())) {
            ++progress;
            if (progress % 500 == 0)
                LOGGER.trace(traceMsg, progress, total, t);
            t.getContextVector().toAssocRateVector(crossTable, rate, true);
        }
    }

    // 4- Clean occurrence indexes in source documents
    LOGGER.debug("4 - Clear occurrence index");
    termIndex.clearOccurrenceIndex();
}