Java com.google.common.collect.Iterators 代码实例

・16 分钟阅读

以下是展示如何使用com.google.common.collect.Iterators的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public Iterator<Object> getChildrenKeysIterator() {
    if (isLeaf()) {
        return Iterators.emptyIterator();
    }
    return Iterators.unmodifiableIterator(keysList.iterator());
}
 

实例 2


protected Iterator<UIComponent> findMatchingTreeNodeComponent(String nodeType, UIComponent parentComponent) {
    Iterator<UIComponent> children = parentComponent.getChildren().iterator();
    if (parentComponent != this) {
        children = Iterators.concat(children, this.getChildren().iterator());
    }
    return Iterators.filter(children, new MatchingTreeNodePredicate(nodeType));
}
 

实例 3


@Override
public void broadcast(BehaviorEvent event) throws AbortProcessingException {
    // Add message components to re-render list ( if any )
    FacesContext facesContext = FacesContext.getCurrentInstance();
    PartialViewContext partialViewContext = facesContext.getPartialViewContext();
    if (partialViewContext.isAjaxRequest()) {
        UIComponent component = event.getComponent();
        if (component instanceof EditableValueHolder) {
            String clientId = component.getClientId(facesContext);
            final ImmutableList<Message> messages = ImmutableList.copyOf(Iterators.transform(facesContext.getMessages(clientId), MESSAGES_TRANSFORMER));
            JavaScriptService javaScriptService = ServiceTracker.getService(JavaScriptService.class);
            javaScriptService.addPageReadyScript(facesContext, new MessageUpdateScript(clientId, messages));
            if (messages.isEmpty()) {
                final String onvalid = getOnvalid();
                if (onvalid != null && !"".equals(onvalid.trim())) {
                    javaScriptService.addPageReadyScript(facesContext, new AnonymousFunctionCall().addToBody(onvalid));
                }
            } else {
                final String oninvalid = getOninvalid();
                if (oninvalid != null && !"".equals(oninvalid.trim())) {
                    javaScriptService.addPageReadyScript(facesContext, new AnonymousFunctionCall("messages").addParameterValue(ScriptUtils.toScript(messages)).addToBody(oninvalid));
                }
            }
        }
    }
    super.broadcast(event);
}
 

实例 4


/**
 * Returns clientIds of component for which validation has failed and adds form's clientId at the end (as a fallback if
 * there is no invalid component or none of invalid components won't be focusable on the client).
 */
private String[] getClientIdsWithMessages(FacesContext context, UIForm form) {
     Iterator<String> clientIdsWithMessages = Iterators.filter(context.getClientIdsWithMessages(), new Predicate<String>() {
        @Override
        public boolean apply(String input) {
            return input != null;
        }
    });
    return Iterators.toArray(clientIdsWithMessages, String.class);
}
 

实例 5


@Override
protected Iterator<UIComponent> dataChildren() {
    AbstractTreeNode treeNodeComponent = findTreeNodeComponent();
    if (treeNodeComponent != null) {
        return Iterators.<UIComponent> singletonIterator(treeNodeComponent);
    } else {
        return Iterators.<UIComponent> emptyIterator();
    }
}
 

实例 6


public static Converter getSelectItemConverter(Application facesApplication, Iterator<SelectItem> selectItems) {
    Converter converter = null;
    while (selectItems.hasNext() && converter == null) {
        SelectItem selectItem = selectItems.next();
        if (selectItem instanceof SelectItemGroup) {
            SelectItemGroup selectItemGroup = (SelectItemGroup) selectItem;
            Iterator<SelectItem> groupSelectItems = Iterators.forArray(selectItemGroup.getSelectItems());
            // Recursively get the converter from the SelectItems of the SelectItemGroup
            converter = getSelectItemConverter(facesApplication, groupSelectItems);
        }
        else {
            Class<?> selectItemClass = selectItem.getValue().getClass();
            if (String.class.equals(selectItemClass)) {
                return null; // No converter required for strings
            }
            try {
                converter = facesApplication.createConverter(selectItemClass); // Lookup the converter registered for the class
            }
            catch (FacesException exception) {
                // Converter cannot be created
            }
        }
    }
    return converter;
}
 

实例 7


@SuppressWarnings({ "unchecked", "rawtypes" })
public Enumeration getInitParameterNames() {
    Set<String> result = Sets.newHashSet();
    Iterators.addAll(result, (Iterator<? extends String>) defaults.keySet());
    Iterators.addAll(result, Iterators.forEnumeration(config.getInitParameterNames()));
    Iterators.addAll(result, Iterators.forEnumeration(config.getServletContext().getInitParameterNames()));
    return Iterators.asEnumeration(result.iterator());
}
 

实例 8


@Override
@SuppressWarnings("unchecked")
public boolean equals(Object genericRight) {
  if (genericRight instanceof AbstractCounters<?, ?>) {
    return Iterators.elementsEqual(iterator(),
        ((AbstractCounters<C, G>)genericRight).iterator());
  }
  return false;
}
 

实例 9


/**
 * Gets the values at the specified quantiles +/- maxError. The list of quantiles must be sorted
 * in increasing order, and each value must be in the range [0, 1]
 */
public List<Long> getQuantiles(List<Double> quantiles)
{
    checkArgument(Ordering.natural().isOrdered(quantiles), "quantiles must be sorted in increasing order");
    for (double quantile : quantiles) {
        checkArgument(quantile >= 0 && quantile <= 1, "quantile must be between [0,1]");
    }
    final ImmutableList.Builder<Long> builder = ImmutableList.builder();
    final PeekingIterator<Double> iterator = Iterators.peekingIterator(quantiles.iterator());
    postOrderTraversal(root, new Callback()
    {
        private double sum = 0;
        public boolean process(Node node)
        {
            sum += node.weightedCount;
            while (iterator.hasNext() && sum > iterator.peek() * weightedCount) {
                iterator.next();
                // we know the max value ever seen, so cap the percentile to provide better error
                // bounds in this case
                long value = Math.min(node.getUpperBound(), max);
                builder.add(value);
            }
            return iterator.hasNext();
        }
    });
    // we finished the traversal without consuming all quantiles. This means the remaining quantiles
    // correspond to the max known value
    while (iterator.hasNext()) {
        builder.add(max);
        iterator.next();
    }
    return builder.build();
}
 

实例 10


@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Enumeration getParameterNames() {
    Collection<Object> result = Sets.newHashSet();
    Enumeration names = super.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        result.add(name);
    }
    parseIfNecessary();
    result.addAll(params.keySet());
    return Iterators.asEnumeration(result.iterator());
}
 

实例 11


/**
 * It checks that the given reference change is leaded by an ADD or DELETE of the same object.
 * 
 * @param input
 *            The reference change.
 * @return True if it is leaded by an add or delete, False otherwise.
 */
private boolean isLeadedByAddOrDeleteEdge(ReferenceChange input) {
        boolean result = false;
        EObject addedOrDeletedObject = input.getValue();
        EObject container = addedOrDeletedObject.eContainer();
        while (!(container instanceof Edge) && container != null) {
                container = container.eContainer();
        }
        if (container instanceof Edge) {
                result = Iterators.any(input.getMatch().getComparison().getDifferences(container).iterator(),
                                isMainDiffForAddOrDeleteEdge());
        }
        return result;
}
 

实例 12


public SampleTweet() throws IOException {
    ObjectMapper om = new ObjectMapper();
    JsonFactory factory = new JsonFactory();
    ImmutableList.Builder<String> b = ImmutableList.builder();
    InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("sample_tweet.json"));
    try {
        String tweetArray = CharStreams.toString(reader);
        ArrayNode parsed = (ArrayNode)om.readTree(tweetArray);
        for (JsonNode tweet : parsed) {
            StringWriter sw = new StringWriter();
            om.writeTree(factory.createGenerator(sw), tweet);
            b.add(sw.toString());
        }
        sampleTweet = Iterators.cycle(b.build());
    } finally {
        reader.close();
    }
}
 

实例 13


public Location coordIn(CPoint point, CPolygon poly, final double e) {
        return Iterators
                        .getNext(
                                        receiveGeos(
                                                        select(within(gFromT(point), gFromT(poly)),
                                                                        distance(gFromT(point),
                                                                                        boundary(gFromT(poly)))),
                                                        new GeoFactory<Location>() {
                                                                @Override
                                                                public Location createGeo(ResultSet object)
                                                                                throws SQLException {
                                                                        System.out.println(object.getMetaData()
                                                                                        .getColumnCount());
                                                                        return Location.forPosition(
                                                                                        object.getBoolean(1),
                                                                                        (object.getDouble(2) < e));
                                                                }
                                                        }).iterator(), null);
}
 

实例 14


private Iterator<SimpleFeature> applyFeaturesOffsetLimit(Iterator<SimpleFeature> features) {
    if (offset != null) {
        Iterators.advance(features, offset.intValue());
    }
    if (maxFeatures != null) {
        features = Iterators.limit(features, maxFeatures.intValue());
    }
    return features;
}
 

实例 15


/**
 * Override to optimize batch insert.
 */
@Override
public void putAll(final Iterator<? extends RevObject> objects, final BulkOpListener listener) {
    Preconditions.checkState(isOpen(), "No open database connection");
    new DbOp<Void>() {
        @Override
        protected boolean isAutoCommit() {
            return false;
        }
        @Override
        protected Void doRun(Connection cx) throws SQLException, IOException {
            // use INSERT OR IGNORE to deal with duplicates cleanly
            String sql = format("INSERT OR IGNORE INTO %s (object,id) VALUES (?,?)", OBJECTS);
            PreparedStatement stmt = open(cx.prepareStatement(log(sql, LOG)));
            // partition the objects into chunks for batch processing
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Iterator<List<? extends RevObject>> it = (Iterator) Iterators.partition(objects,
                    partitionSize);
            while (it.hasNext()) {
                List<? extends RevObject> objs = it.next();
                for (RevObject obj : objs) {
                    stmt.setBytes(1, ByteStreams.toByteArray(writeObject(obj)));
                    stmt.setString(2, obj.getId().toString());
                    stmt.addBatch();
                }
                notifyInserted(stmt.executeBatch(), objs, listener);
                stmt.clearParameters();
            }
            cx.commit();
            return null;
        }
    }.run(cx);
}
 
讨论
淘淘あ西西 profile image