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:zotmc.collect.delegate.IterativeMap.java

@Override
public Set<Entry<K, V>> entrySet() {
    return entrySet != null ? entrySet : (entrySet = new Set<Entry<K, V>>() {

        @Override/*from  ww  w  .  j  a v a  2 s.c  o  m*/
        public boolean add(Entry<K, V> e) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean addAll(Collection<? extends Entry<K, V>> c) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void clear() {
            backing().clear();
        }

        @Override
        public boolean isEmpty() {
            return backing().isEmpty();
        }

        @SuppressWarnings("unchecked")
        protected Entry<K, V> cast(Object obj) {
            return (Entry<K, V>) obj;
        }

        @Override
        public Iterator<Entry<K, V>> iterator() {
            final Set<K> passed = Sets.newHashSet();
            final Predicate<Entry<K, V>> keyNotInPassed = new Predicate<Entry<K, V>>() {
                @Override
                public boolean apply(Entry<K, V> input) {
                    return !passed.contains(input.getKey());
                }
            };

            return new DelegateIterator<Entry<K, V>>() {
                {
                    delegatee = createDelegatee();
                }

                @Override
                protected Iterator<Entry<K, V>> createDelegatee() {
                    return Iterators.filter(backing().iterator(), keyNotInPassed);
                }

                @Override
                protected Iterator<Entry<K, V>> delegatee() {
                    return delegatee;
                }

                @Override
                protected Entry<K, V> passNext() {
                    Entry<K, V> next = super.passNext();
                    passed.add(next.getKey());
                    return next;
                }

                @Override
                public void remove() {
                    IterativeMap.this.remove(last());
                    delegatee = createDelegatee();
                }
            };
        }

        @Override
        public boolean contains(Object o) {
            Entry<K, V> entry = cast(o);
            try {
                for (Entry<K, V> b : backing())
                    if (b.getKey().equals(entry.getKey()))
                        return b.getValue().equals(entry.getValue());
            } catch (NullPointerException ignored) {
            } catch (ClassCastException ignored) {
            }

            return false;
        }

        @Override
        public boolean containsAll(Collection<?> c) {
            return Sets.newHashSet(this).containsAll(c);
        }

        @Override
        public boolean remove(Object o) {
            if (contains(o)) {
                IterativeMap.this.remove(cast(o).getKey());
                return true;
            }
            return false;
        }

        @Override
        public boolean removeAll(Collection<?> c) {
            return StandardImpls.CollectionImpl.removeAll(this, c);
        }

        @Override
        public boolean retainAll(Collection<?> c) {
            return StandardImpls.CollectionImpl.retainAll(this, c);
        }

        @Override
        public int size() {
            return Iterators.size(iterator());
        }

        @Override
        public Object[] toArray() {
            return StandardImpls.CollectionImpl.toArray(this);
        }

        @Override
        public <T> T[] toArray(T[] a) {
            return StandardImpls.CollectionImpl.toArray(this, a);
        }

        @Override
        public int hashCode() {
            return StandardImpls.SetImpl.hashCode(this);
        }

        @Override
        public boolean equals(Object obj) {
            return Sets.newHashSet(this).equals(obj);
        }

        @Override
        public String toString() {
            return StandardImpls.SetImpl.toString(this);
        }
    });
}

From source file:org.jclouds.examples.cloudwatch.basics.MainApp.java

/**
 * Return an array of doubles with the CPUUtilization {@link EC2Constants.MetricName#CPU_UTILIZATION}
 * average, maximum and minimum values in respective order over the last 24 hours.
 *
 * @param metricClient the {@link MetricClient} to use
 * @param nodeId the instance id whose CPUUtilization statistics we're intersted in calculating
 *
 * @return the array of doubles describe above or null if there are no CPUUtilization metrics stored for the given
 * instance id over the past 24 hours//from   w  w  w.  j  a  v  a 2 s. c om
 */
private static double[] getCPUUtilizationStatsForInstanceOverTheLast24Hours(MetricClient metricClient,
        String nodeId) {

    Dimension instanceIdDimension = new Dimension(EC2Constants.Dimension.INSTANCE_ID, nodeId);
    ListMetricsOptions lmOptions = ListMetricsOptions.builder()
            // Only return metrics if they are CPUUtilization
            .metricName(EC2Constants.MetricName.CPU_UTILIZATION)
            // Only return metrics for the AWS/EC2 namespace
            .namespace(Namespaces.EC2)
            // Only return metrics for the given instance
            .dimension(instanceIdDimension).build();

    // Return null to indicate there are no CPUUtilization metrics stored for the given node id
    if (Iterators.size(metricClient.listMetrics(lmOptions).iterator()) == 0) {
        return null;
    }

    Date endDate = new Date(); // Now
    Date startDate = new Date(endDate.getTime() - (1000 * 60 * 60 * 24)); // One day ago
    GetMetricStatistics statistics = GetMetricStatistics.builder()
            // Specify the instance id you're interested in
            .dimension(instanceIdDimension)
            // Specify the metric name you're interested in
            .metricName(EC2Constants.MetricName.CPU_UTILIZATION)
            // Specify the namespace of the metric
            .namespace(Namespaces.EC2)
            // Populate the average statistic in the response
            .statistic(Statistics.AVERAGE)
            // Populate the maximum statistic in the response
            .statistic(Statistics.MAXIMUM)
            // Populate the minimum statistic in the response
            .statistic(Statistics.MINIMUM)
            // Specify the start time for the metric statistics you want
            .startTime(startDate)
            // Specify the end time for the metric statistics you want
            .endTime(endDate)
            // Specify the metric statistic granularity
            .period(3600)
            // Specify the unit the metric values should be in
            .unit(Unit.PERCENT).build();
    GetMetricStatisticsResponse statisticsResponse = metricClient.getMetricStatistics(statistics);
    double avg = 0d;
    double max = 0d;
    double min = 0d;
    Iterator<Datapoint> datapointIterator = statisticsResponse.iterator();

    while (datapointIterator.hasNext()) {
        Datapoint datapoint = datapointIterator.next();
        Double dAvg = datapoint.getAverage();
        Double dMax = datapoint.getMaximum();
        Double dMin = datapoint.getMinimum();

        if (dAvg != null) {
            avg = ((avg + dAvg) / 2);
        }
        if (dMax != null) {
            if (dMax > max) {
                max = dMax;
            }
        }
        if (dMin != null) {
            if (dMin < min) {
                min = dMin;
            }
        }
    }

    return new double[] { avg, max, min };

}

From source file:org.gitools.matrix.model.iterable.AbstractIterable.java

@Override
public int count() {
    return Iterators.size(iterator());
}

From source file:org.apache.giraph.comm.messages.ByteArrayMessagesPerVertexStore.java

@Override
protected int getNumberOfMessagesIn(ConcurrentMap<I, DataInputOutput> partitionMap) {
    int numberOfMessages = 0;
    for (DataInputOutput dataInputOutput : partitionMap.values()) {
        numberOfMessages += Iterators
                .size(new RepresentativeByteStructIterator<M>(dataInputOutput.createDataInput()) {
                    @Override/*from   w  w  w .  jav a2  s .c o  m*/
                    protected M createWritable() {
                        return messageValueFactory.newInstance();
                    }
                });
    }
    return numberOfMessages;
}

From source file:com.inductiveautomation.reporting.examples.datasource.common.RestJsonDataSource.java

/**
 * Looks through the {@link JSONArray}, evaluating each {@link JSONObject} to determine which has the largest
 * set of keys.  This process is useful because not all JSON objects in an array may have the same key set.  There
 * are some assumptions made that the largest keyset will contain all the keys available in those of lower sets.
 * This is far from true, but this assumption is allowed for the sake of simplicity for this example.
 * @param jsonArray a {@link JSONArray}// www  .  j av a  2  s . com
 * @return a JSONObject containing the most keys found in the array.  May be empty.
 */
private JSONObject findReferenceObjectIndex(JSONArray jsonArray) throws JSONException {
    JSONObject reference = null;
    if (jsonArray != null && jsonArray.length() > 0) {
        reference = jsonArray.getJSONObject(0);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jo = jsonArray.getJSONObject(i);
            if (Iterators.size(jo.keys()) > Iterators.size(reference.keys())) {
                reference = jo;
            }
        }
    }
    return reference == null ? new JSONObject() : reference;
}

From source file:org.eclipse.incquery.runtime.localsearch.matcher.LocalSearchMatcher.java

public int countMatches(MatchingFrame initialFrame) throws LocalSearchException {
    matchingStarted();//from  ww w.ja v a2 s.c o m
    PlanExecutionIterator it = new PlanExecutionIterator(plan, initialFrame, adapters);
    int result = Iterators.size(it);
    matchingFinished();
    return result;
}

From source file:org.graylog2.restclient.lib.ServerNodes.java

public int connectedNodesCount() {
    return Iterators.size(skipInactive(serverNodes));
}

From source file:org.eclipse.sirius.business.api.control.SiriusUncontrolCommand.java

private boolean airdResourceHasNoRepresentations(final Resource childAirdResource) {
    return Iterators.size(Iterators.filter(EcoreUtil.getAllProperContents(childAirdResource, true),
            DRepresentation.class)) == 0;
}

From source file:org.onosproject.incubator.net.virtual.impl.VirtualNetworkIntentService.java

@Override
public long getIntentCount() {
    return Iterators.size(getIntents().iterator());
}

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

private void logStats() {
    Ordering<String> a = Ordering.natural().reverse().onResultOf(Functions.forMap(counters))
            .compound(Ordering.natural());
    Map<String, MutableInt> map = ImmutableSortedMap.copyOf(counters, a);

    Iterator<Entry<String, MutableInt>> it = map.entrySet().iterator();
    if (it.hasNext()) {// it will be empty if pipeline is run on empty collection
        Entry<String, MutableInt> mostFrequentAnno = it.next();
        LOGGER.info("[{}] {}: {} ", statName, mostFrequentAnno.getKey(),
                mostFrequentAnno.getValue().intValue());
    }/*w  w w  . j a  v a 2s . com*/
    int nbSyntacticVariants = 0;
    int nbMorphologicalVariants = 0;
    int nbGraphicalVariants = 0;
    int nbOccurrences = 0;
    int nbPrimaryOccOccurrences = 0;
    TermIndex tIndex = termIndexResource.getTermIndex();
    for (Term t : tIndex.getTerms()) {
        nbMorphologicalVariants += Iterables.size(t.getVariations(VariationType.MORPHOLOGICAL));
        nbSyntacticVariants += Iterables.size(t.getVariations(VariationType.SYNTACTICAL));
        nbGraphicalVariants += Iterables.size(t.getVariations(VariationType.GRAPHICAL));
        nbOccurrences += t.getOccurrences().size();
        for (TermOccurrence o : t.getOccurrences()) {
            if (o.isPrimaryOccurrence())
                nbPrimaryOccOccurrences++;
        }
    }
    // graphical variants are bidirectional
    nbGraphicalVariants /= 2;

    LOGGER.info("[{}] Nb terms:    {} [sw: {}, mw: {}]", statName, tIndex.getTerms().size(),
            Iterators.size(tIndex.singleWordTermIterator()), Iterators.size(tIndex.multiWordTermIterator()));
    LOGGER.info("[{}] Nb words:    {} [compounds: {}]", statName, tIndex.getWords().size(),
            Iterators.size(tIndex.compoundWordTermIterator()));
    LOGGER.info("[{}] Nb occurrences: {} [primary: {}]", statName, nbOccurrences, nbPrimaryOccOccurrences);
    LOGGER.info("[{}] Nb variants: {} [morph: {}, syn: {}, graph: {}]", statName,
            nbMorphologicalVariants + nbSyntacticVariants + nbGraphicalVariants, nbMorphologicalVariants,
            nbSyntacticVariants, nbGraphicalVariants);
}