类java.util.Collection源码实例Demo

下面列出了怎么用java.util.Collection的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: crate   文件: LuceneQueryBuilder.java
static Query genericFunctionFilter(Function function, Context context) {
    if (function.valueType() != DataTypes.BOOLEAN) {
        raiseUnsupported(function);
    }
    // rewrite references to source lookup instead of using the docValues column store if:
    // - no docValues are available for the related column, currently only on objects defined as `ignored`
    // - docValues value differs from source, currently happening on GeoPoint types as lucene's internal format
    //   results in precision changes (e.g. longitude 11.0 will be 10.999999966)
    function = (Function) DocReferences.toSourceLookup(function,
        r -> r.columnPolicy() == ColumnPolicy.IGNORED
             || r.valueType() == DataTypes.GEO_POINT);

    final InputFactory.Context<? extends LuceneCollectorExpression<?>> ctx = context.docInputFactory.getCtx(context.txnCtx);
    @SuppressWarnings("unchecked")
    final Input<Boolean> condition = (Input<Boolean>) ctx.add(function);
    final Collection<? extends LuceneCollectorExpression<?>> expressions = ctx.expressions();
    final CollectorContext collectorContext = new CollectorContext();
    for (LuceneCollectorExpression<?> expression : expressions) {
        expression.startCollect(collectorContext);
    }
    return new GenericFunctionQuery(function, expressions, condition);
}
 
源代码2 项目: accumulo-recipes   文件: AccumuloFeatureStore.java
protected ScannerBase metricScanner(AccumuloFeatureConfig xform, Date start, Date end, String group, Iterable<String> types, String name, TimeUnit timeUnit, Auths auths) {
    checkNotNull(xform);

    try {
        group = defaultString(group);
        timeUnit = (timeUnit == null ? TimeUnit.MINUTES : timeUnit);

        BatchScanner scanner = connector.createBatchScanner(tableName + REVERSE_SUFFIX, auths.getAuths(), config.getMaxQueryThreads());

        Collection<Range> typeRanges = new ArrayList();
        for (String type : types)
            typeRanges.add(buildRange(type, start, end, timeUnit));

        scanner.setRanges(typeRanges);
        scanner.fetchColumn(new Text(combine(timeUnit.toString(), xform.featureName())), new Text(combine(group, name)));

        return scanner;

    } catch (TableNotFoundException e) {
        throw new RuntimeException(e);
    }
}
 
源代码3 项目: geowave   文件: DBScanJobRunner.java
@Override
public Collection<ParameterEnum<?>> getParameters() {
  final Collection<ParameterEnum<?>> params = super.getParameters();
  params.addAll(
      Arrays.asList(
          new ParameterEnum<?>[] {
              Partition.PARTITIONER_CLASS,
              Partition.MAX_DISTANCE,
              Partition.MAX_MEMBER_SELECTION,
              Global.BATCH_ID,
              Hull.DATA_TYPE_ID,
              Hull.PROJECTION_CLASS,
              Clustering.MINIMUM_SIZE,
              Partition.GEOMETRIC_DISTANCE_UNIT,
              Partition.DISTANCE_THRESHOLDS}));
  return params;
}
 
源代码4 项目: pcgen   文件: ArmortypeToken.java
@Override
public String[] unparse(LoadContext context, EquipmentModifier mod)
{
	Changes<ChangeArmorType> changes = context.getObjectContext().getListChanges(mod, ListKey.ARMORTYPE);
	Collection<ChangeArmorType> added = changes.getAdded();
	if (added == null || added.isEmpty())
	{
		// Zero indicates no Token
		return null;
	}
	TreeSet<String> set = new TreeSet<>();
	for (ChangeArmorType cat : added)
	{
		set.add(cat.getLSTformat());
	}
	return set.toArray(new String[0]);
}
 
源代码5 项目: n4js   文件: IssueExpectations.java
/**
 * Matches the expectations in the added issues matchers against the given issues.
 *
 * @param issues
 *            the issues to match the expectations against
 * @param messages
 *            if this parameter is not <code>null</code>, this method will add an explanatory message for each
 *            mismatch
 * @return <code>true</code> if and only if every expectation was matched against an issue
 */
public boolean matchesAllExpectations(Collection<Issue> issues, List<String> messages) {
	Collection<Issue> issueCopy = new LinkedList<>(issues);
	Collection<IssueMatcher> matcherCopy = new LinkedList<>(issueMatchers);

	performMatching(issueCopy, matcherCopy, messages);
	if (inverted) {
		if (matcherCopy.isEmpty()) {
			explainExpectations(issueMatchers, messages, inverted);
			return false;
		}
	} else {
		if (!matcherCopy.isEmpty()) {
			explainExpectations(matcherCopy, messages, inverted);
			return false;
		}
	}
	return false;
}
 
源代码6 项目: Flink-CEPplus   文件: AccumulatorHelper.java
public static String getResultsFormatted(Map<String, Object> map) {
	StringBuilder builder = new StringBuilder();
	for (Map.Entry<String, Object> entry : map.entrySet()) {
		builder
			.append("- ")
			.append(entry.getKey())
			.append(" (")
			.append(entry.getValue().getClass().getName())
			.append(")");
		if (entry.getValue() instanceof Collection) {
			builder.append(" [").append(((Collection) entry.getValue()).size()).append(" elements]");
		} else {
			builder.append(": ").append(entry.getValue().toString());
		}
		builder.append(System.lineSeparator());
	}
	return builder.toString();
}
 
源代码7 项目: codeu_project_2017   文件: View.java
@Override
public Collection<Message> getMessages(Uuid conversation, Time start, Time end) {

  final Collection<Message> messages = new ArrayList<>();

  try (final Connection connection = source.connect()) {

    Serializers.INTEGER.write(connection.out(), NetworkCode.GET_MESSAGES_BY_TIME_REQUEST);
    Time.SERIALIZER.write(connection.out(), start);
    Time.SERIALIZER.write(connection.out(), end);

    if (Serializers.INTEGER.read(connection.in()) == NetworkCode.GET_MESSAGES_BY_TIME_RESPONSE) {
      messages.addAll(Serializers.collection(Message.SERIALIZER).read(connection.in()));
    } else {
      LOG.error("Response from server failed.");
    }

  } catch (Exception ex) {
    System.out.println("ERROR: Exception during call on server. Check log for details.");
    LOG.error(ex, "Exception during call on server.");
  }

  return messages;
}
 
源代码8 项目: pinpoint   文件: MetricRegistry.java
public Collection<HistogramSnapshot> createRpcResponseSnapshot() {
    final List<HistogramSnapshot> histogramSnapshotList = new ArrayList<HistogramSnapshot>(16);
    for (RpcMetric metric : rpcCache.values()) {
        histogramSnapshotList.addAll(metric.createSnapshotList());
    }
    return histogramSnapshotList;
}
 
/**
 * Only those who have any of the given roles can access the protected instance.
 *
 * @param roles The roles to check for.
 * @return A newly created AccessPredicate that only returns true, if the name of the {@link GrantedAuthority}s
 *         matches any of the given role names.
 */
static AccessPredicate hasAnyRole(final Collection<String> roles) {
    requireNonNull(roles, "roles");
    roles.forEach(role -> requireNonNull(role, "role"));
    final Set<String> immutableRoles = ImmutableSet.copyOf(roles);
    return authentication -> {
        for (final GrantedAuthority authority : authentication.getAuthorities()) {
            if (immutableRoles.contains(authority.getAuthority())) {
                return true;
            }
        }
        return false;
    };
}
 
public Action createContextAwareInstance(Lookup actionContext) {
    Collection<? extends BreakpointAnnotation> ann = actionContext.lookupAll(BreakpointAnnotation.class);
    if (ann.size() > 0) {
        onBreakpoint = true;
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                onBreakpoint = false;
            }
        });
        return getAction();
    } else {
        return this;
    }
}
 
源代码11 项目: pravega   文件: ContainerTableExtensionImpl.java
@Override
public Collection<WriterSegmentProcessor> createWriterSegmentProcessors(UpdateableSegmentMetadata metadata) {
    Exceptions.checkNotClosed(this.closed.get(), this);
    if (!metadata.getAttributes().containsKey(TableAttributes.INDEX_OFFSET)) {
        // Not a Table Segment; nothing to do.
        return Collections.emptyList();
    }

    return Collections.singletonList(new WriterTableProcessor(new TableWriterConnectorImpl(metadata), this.executor));
}
 
public PartitionMessageWithDirectReply(
    Collection<InternalDistributedMember> recipients, int regionId,
    DirectReplyProcessor processor, final TXStateInterface tx) {
  super(recipients, regionId, processor, tx);
  this.processor = processor;
  this.posDup = false;
}
 
源代码13 项目: TencentKona-8   文件: TypeModeler.java
public static Collection<DeclaredType> collectInterfaces(TypeElement type) {
    @SuppressWarnings({"unchecked"})
    Collection<DeclaredType> interfaces = (Collection<DeclaredType>) type.getInterfaces();
    for (TypeMirror interfaceType : type.getInterfaces()) {
        interfaces.addAll(collectInterfaces(getDeclaration(interfaceType)));
    }
    return interfaces;
}
 
/**
 * Computes the necessary equality constraints for conditional expressions.
 *
 * @param constraints the type constraints (element type: <code>ITypeConstraint2</code>)
 * @param level the compliance level
 */
private void computeConditionalTypeConstraints(final Collection<ITypeConstraint2> constraints, final int level) {
	ITypeConstraint2 constraint= null;
	for (final Iterator<ITypeConstraint2> iterator= constraints.iterator(); iterator.hasNext();) {
		constraint= iterator.next();
		if (constraint instanceof ConditionalTypeConstraint) {
			final ConditionalTypeConstraint conditional= (ConditionalTypeConstraint) constraint;
			fModel.createEqualityConstraint(constraint.getLeft(), constraint.getRight());
			fModel.createEqualityConstraint(conditional.getExpression(), constraint.getLeft());
			fModel.createEqualityConstraint(conditional.getExpression(), constraint.getRight());
		}
	}
}
 
源代码15 项目: RDFUnit   文件: RdfUnitJunitRunner.java
private Collection<GenericTestCase> createTestCases() throws InitializationError {
    return new RDFUnitTestSuiteGenerator.Builder()
            .addSchemaURI("custom", getSchema().uri(), getSchemaReader())
            .enableAutotests()
            .build()
                .getTestSuite()
                    .getTestCases();
}
 
源代码16 项目: neoscada   文件: X509CA.java
public X509CA ( final CertificateFactory cf, final String certificateUrl, final Collection<String> crlUrls )
{
    this.certificateFactory = cf;
    this.certificateUrl = certificateUrl;
    this.crlUrls = crlUrls != null ? new ArrayList<String> ( crlUrls ) : null;

    this.certificates = new X509Certificate[0];
    this.crls = new X509CRL[0];
}
 
源代码17 项目: fenixedu-academic   文件: ExecutionDegree.java
@Override
protected void checkForDeletionBlockers(Collection<String> blockers) {
    super.checkForDeletionBlockers(blockers);
    if (!(getSchoolClassesSet().isEmpty() && getGuidesSet().isEmpty() && getStudentCandidaciesSet().isEmpty() && getShiftDistributionEntriesSet()
            .isEmpty())) {
        blockers.add(BundleUtil.getString(Bundle.APPLICATION, "execution.degree.cannot.be.deleted"));
    }
}
 
源代码18 项目: libreveris   文件: BasicNest.java
@Override
public synchronized Collection<Glyph> getActiveGlyphs ()
{
    if (activeGlyphs == null) {
        activeGlyphs = Glyphs.sortedSet(activeMap.values());
        activeGlyphs.addAll(virtualGlyphs);
    }

    return Collections.unmodifiableCollection(activeGlyphs);
}
 
源代码19 项目: Tomcat8-Source-Read   文件: ResponseUtil.java
@Override
public Collection<String> getHeaders(String name) {
    Enumeration<String> values = headers.values(name);
    List<String> result = new ArrayList<>();
    while (values.hasMoreElements()) {
        result.add(values.nextElement());
    }
    return result;
}
 
源代码20 项目: gemfirexd-oss   文件: ParameterBindingTest.java
public void testBindCollectionInFromClause() throws Exception {
  Query query = CacheUtils.getQueryService().newQuery("SELECT DISTINCT * FROM $1 ");
  Object params[] = new Object[1];
  Region region = CacheUtils.getRegion("/Portfolios");
  params[0] = region.values();
  Object result = query.execute(params);
  if(result instanceof Collection){
    int resultSize = ((Collection)result).size();
    if( resultSize != region.values().size())
      fail("Results not as expected");
  }else
    fail("Invalid result");
}
 
源代码21 项目: jpmml-evaluator   文件: Classification.java
static
public <K, V extends Number> Map.Entry<K, Value<V>> getWinner(Type type, Collection<Map.Entry<K, Value<V>>> entries){
	Ordering<Map.Entry<K, Value<V>>> ordering = Classification.<K, V>createOrdering(type);

	try {
		return ordering.max(entries);
	} catch(NoSuchElementException nsee){
		return null;
	}
}
 
源代码22 项目: RipplePower   文件: DecodedBitStreamParser.java
private static void decodeByteSegment(BitSource bits, StringBuilder result, int count,
		CharacterSetECI currentCharacterSetECI, Collection<byte[]> byteSegments, Map<DecodeHintType, ?> hints)
		throws FormatException {
	// Don't crash trying to read more bits than we have available.
	if (8 * count > bits.available()) {
		throw FormatException.getFormatInstance();
	}

	byte[] readBytes = new byte[count];
	for (int i = 0; i < count; i++) {
		readBytes[i] = (byte) bits.readBits(8);
	}
	String encoding;
	if (currentCharacterSetECI == null) {
		// The spec isn't clear on this mode; see
		// section 6.4.5: t does not say which encoding to assuming
		// upon decoding. I have seen ISO-8859-1 used as well as
		// Shift_JIS -- without anything like an ECI designator to
		// give a hint.
		encoding = StringUtils.guessEncoding(readBytes, hints);
	} else {
		encoding = currentCharacterSetECI.name();
	}
	try {
		result.append(new String(readBytes, encoding));
	} catch (UnsupportedEncodingException ignored) {
		throw FormatException.getFormatInstance();
	}
	byteSegments.add(readBytes);
}
 
源代码23 项目: triplea   文件: MoveValidator.java
private Optional<String> canAnyPassThroughCanal(
    final CanalAttachment canalAttachment,
    final Collection<Unit> units,
    final GamePlayer player) {
  if (units.stream().anyMatch(Matches.unitIsOfTypes(canalAttachment.getExcludedUnits()))) {
    return Optional.empty();
  }
  return checkCanalStepAndOwnership(canalAttachment, player);
}
 
源代码24 项目: mrgeo   文件: MinAvgPairAggregator.java
@Override
public short aggregate(short[] values, short nodata)
{
  boolean data0 = values[0] != nodata;
  boolean data1 = values[1] != nodata;
  boolean data2 = values[2] != nodata;
  boolean data3 = values[3] != nodata;

  Collection<Integer> averages = new ArrayList<>();
  if (data0 && data1)
  {
    averages.add((values[0] + values[1]) / 2);
  }
  if (data0 && data2)
  {
    averages.add((values[0] + values[2]) / 2);
  }
  if (data0 && data3)
  {
    averages.add((values[0] + values[3]) / 2);
  }
  if (data1 && data2)
  {
    averages.add((values[1] + values[2]) / 2);
  }
  if (data1 && data3)
  {
    averages.add((values[1] + values[3]) / 2);
  }
  if (data2 && data3)
  {
    averages.add((values[2] + values[3]) / 2);
  }

  return (averages.isEmpty()) ? nodata : Collections.min(averages).shortValue();
}
 
源代码25 项目: ovsdb   文件: AbstractTransactCommand.java
@SuppressWarnings("checkstyle:IllegalCatch")
public AbstractTransactCommand getClone() {
    try {
        return getClass().getConstructor(HwvtepOperationalState.class, Collection.class)
                .newInstance(hwvtepOperationalState, changes);
    } catch (Throwable e) {
        LOG.error("Failed to clone the cmd ", e);
    }
    return this;
}
 
源代码26 项目: ontopia   文件: ResourcesDirectoryReader.java
public Collection<String> getResourcesAsStrings() {
  if (resources == null) {
    findResources();
  }
  return CollectionUtils.collect(resources, new Transformer<URL, String>() {
    @Override
    public String transform(URL url) {
      try {
        return URLDecoder.decode(url.toString(), "utf-8");
      } catch (UnsupportedEncodingException uee) {
        throw new OntopiaRuntimeException(uee);
      }
    }
  });
}
 
源代码27 项目: gatk-protected   文件: SeqGraph.java
/**
 * Zip up all of the simple linear chains present in this graph.
 *
 * Merges together all pairs of vertices in the graph v1 -> v2 into a single vertex v' containing v1 + v2 sequence
 *
 * Only works on vertices where v1's only outgoing edge is to v2 and v2's only incoming edge is from v1.
 *
 * If such a pair of vertices is found, they are merged and the graph is update.  Otherwise nothing is changed.
 *
 * @return true if any such pair of vertices could be found, false otherwise
 */
public boolean zipLinearChains() {
    // create the list of start sites [doesn't modify graph yet]
    final Collection<SeqVertex> zipStarts = new LinkedList<>();
    for ( final SeqVertex source : vertexSet() ) {
        if ( isLinearChainStart(source) ) {
            zipStarts.add(source);
        }
    }

    if ( zipStarts.isEmpty() ) // nothing to do, as nothing could start a chain
    {
        return false;
    }

    // At this point, zipStarts contains all of the vertices in this graph that might start some linear
    // chain of vertices.  We walk through each start, building up the linear chain of vertices and then
    // zipping them up with mergeLinearChain, if possible
    boolean mergedOne = false;
    for ( final SeqVertex zipStart : zipStarts ) {
        final LinkedList<SeqVertex> linearChain = traceLinearChain(zipStart);

        // merge the linearized chain, recording if we actually did some useful work
        mergedOne |= mergeLinearChain(linearChain);
    }

    return mergedOne;
}
 
源代码28 项目: tez   文件: TimelineCachePluginImpl.java
@Override
public Set<TimelineEntityGroupId> getTimelineEntityGroupId(String entityType,
    NameValuePair primaryFilter,
    Collection<NameValuePair> secondaryFilters) {
  if (!knownEntityTypes.contains(entityType)
      || primaryFilter == null
      || !knownEntityTypes.contains(primaryFilter.getName())
      || summaryEntityTypes.contains(entityType)) {
    return null;
  }
  return convertToTimelineEntityGroupIds(primaryFilter.getName(), primaryFilter.getValue().toString());
}
 
源代码29 项目: james-project   文件: MailDelivrerTest.java
@Test
public void deliverShouldWork() throws Exception {
    Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();

    UnmodifiableIterator<HostAddress> dnsEntries = ImmutableList.of(
        HOST_ADDRESS_1,
        HOST_ADDRESS_2).iterator();
    when(dnsHelper.retrieveHostAddressIterator(MailAddressFixture.JAMES_APACHE_ORG)).thenReturn(dnsEntries);
    when(mailDelivrerToHost.tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class)))
        .thenReturn(ExecutionResult.success());
    ExecutionResult executionResult = testee.deliver(mail);

    verify(mailDelivrerToHost, times(1)).tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class));
    assertThat(executionResult.getExecutionState()).isEqualTo(ExecutionResult.ExecutionState.SUCCESS);
}
 
源代码30 项目: crate   文件: Filter.java
@Override
public LogicalPlan pruneOutputsExcept(TableStats tableStats, Collection<Symbol> outputsToKeep) {
    LinkedHashSet<Symbol> toKeep = new LinkedHashSet<>(outputsToKeep);
    SymbolVisitors.intersection(query, source.outputs(), toKeep::add);
    LogicalPlan newSource = source.pruneOutputsExcept(tableStats, toKeep);
    if (newSource == source) {
        return this;
    }
    return new Filter(newSource, query);
}
 
 类所在包
 同包方法