当前位置: 首页>>代码示例>>Java>>正文


Java Supplier类代码示例

本文整理汇总了Java中java.util.function.Supplier的典型用法代码示例。如果您正苦于以下问题:Java Supplier类的具体用法?Java Supplier怎么用?Java Supplier使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Supplier类属于java.util.function包,在下文中一共展示了Supplier类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: SourceLevelSelector

import java.util.function.Supplier; //导入依赖的package包/类
SourceLevelSelector(
        @NonNull final PropertyEvaluator eval,
        @NonNull final String sourceLevelPropName,
        @NonNull final List<? extends Supplier<? extends ClassPath>> cpFactories) {
    Parameters.notNull("eval", eval);   //NOI18N
    Parameters.notNull("sourceLevelPropName", sourceLevelPropName); //NOI18N
    Parameters.notNull("cpFactories", cpFactories); //NOI18N
    if (cpFactories.size() != 2) {
        throw new IllegalArgumentException("Invalid classpaths: " + cpFactories);  //NOI18N
    }
    for (Supplier<?> f : cpFactories) {
        if (f == null) {
            throw new NullPointerException("Classpaths contain null: " + cpFactories);  //NOI18N
        }
    }
    this.eval = eval;
    this.sourceLevelPropName = sourceLevelPropName;
    this.cpfs = cpFactories;
    this.listeners = new PropertyChangeSupport(this);
    this.cps = new ClassPath[2];
    this.eval.addPropertyChangeListener(WeakListeners.propertyChange(this, this.eval));
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:ClassPathProviderImpl.java

示例2: getApplicableEvents

import java.util.function.Supplier; //导入依赖的package包/类
/**
 * Computes applicable events.
 *
 * @param <AggregateT>           The aggregate over which the query executes
 * @param <EventIdT>             The type of the {@link EventT}'s id field
 * @param <EventT>               The type of the Event
 * @param <SnapshotIdT>          The type of the {@link SnapshotT}'s id field
 * @param <SnapshotT>            The type of the Snapshot
 * @param forwardOnlyEvents      Known forward only events
 * @param executor               An instance of Executor
 * @param snapshotAndEventsSince Events to use if forwardOnlyEvents is empty
 *
 * @return events that can be applied.
 */
public static <
        AggregateT,
        EventIdT,
        EventT extends BaseEvent<AggregateT, EventIdT, EventT>,
        SnapshotIdT,
        SnapshotT extends BaseSnapshot<AggregateT, SnapshotIdT, EventIdT, EventT>
        > Flowable<EventT> getApplicableEvents(
        Flowable<EventT> forwardOnlyEvents, Executor executor,
        Supplier<Flowable<Pair<SnapshotT, List<EventT>>>> snapshotAndEventsSince) {
    return forwardOnlyEvents
            .filter(e -> e instanceof Deprecates)
            .toList()
            .toFlowable()
            .flatMap(list -> list.isEmpty() ?
                    forwardOnlyEvents :
                    snapshotAndEventsSince.get().flatMap(p ->
                            getForwardOnlyEvents(p.getSecond(), executor, () ->
                                    error(new GroovesException(
                                            "Couldn't apply deprecates events")))
                    ));
}
 
开发者ID:rahulsom,项目名称:grooves,代码行数:36,代码来源:Utils.java

示例3: makePerformanceRateUuidValidator

import java.util.function.Supplier; //导入依赖的package包/类
/**
 * Method for Performance Rate Uuid validations
 *
 * @param check a property existence check
 * @param keys that identify measures
 * @return a callback / consumer that will perform a measure specific validation against a given
 * node.
 */
private Consumer<Node> makePerformanceRateUuidValidator(Supplier<String> check, String... keys) {
	return node -> {
		if (check.get() != null) {
			Predicate<Node> childUuidFinder =
					makeUuidChildFinder(check, ErrorCode.QUALITY_MEASURE_ID_MISSING_SINGLE_PERFORMANCE_RATE, PERFORMANCE_RATE_ID);

			Node existingUuidChild = node
					.getChildNodes(TemplateId.PERFORMANCE_RATE_PROPORTION_MEASURE)
					.filter(childUuidFinder)
					.findFirst()
					.orElse(null);

			if (existingUuidChild == null) {
				addMeasureConfigurationValidationMessage(check, keys, node);
			}
		}
	};
}
 
开发者ID:CMSgov,项目名称:qpp-conversion-tool,代码行数:27,代码来源:CpcQualityMeasureIdValidator.java

示例4: testGenerator

import java.util.function.Supplier; //导入依赖的package包/类
@Test
public void testGenerator() {
    final String prefix1 = "http://example.org/";
    final String prefix2 = "trellis:repository/a/b/c/";
    final IdentifierService svc = new UUIDGenerator();
    final Supplier<String> gen1 = svc.getSupplier(prefix1);
    final Supplier<String> gen2 = svc.getSupplier(prefix2);

    final String id1 = gen1.get();
    final String id2 = gen2.get();

    assertTrue(id1.startsWith(prefix1));
    assertFalse(id1.equals(prefix1));
    assertTrue(id2.startsWith(prefix2));
    assertFalse(id2.equals(prefix2));
}
 
开发者ID:trellis-ldp,项目名称:trellis,代码行数:17,代码来源:IdServiceTest.java

示例5: queryAndApply

import java.util.function.Supplier; //导入依赖的package包/类
/**
 * Applies the {@code pageMapper} function on each page fetched from the supplied {@code queryRequestSupplier} on
 * the supplied {@code ctpClient}.
 *
 * @param ctpClient            defines the CTP project to apply the query on.
 * @param queryRequestSupplier defines a supplier which, when executed, returns the query that should be made on
 *                             the CTP project.
 * @param resourceMapper       defines a mapper function that should be applied on each resource in the fetched page
 *                             from the query on the specified CTP project.
 */
public static <T extends Resource, C extends QueryDsl<T, C>> void queryAndApply(
    @Nonnull final SphereClient ctpClient,
    @Nonnull final Supplier<QueryDsl<T, C>> queryRequestSupplier,
    @Nonnull final Function<T, SphereRequest<T>> resourceMapper) {

    final Function<List<T>, Stream<CompletableFuture<T>>> pageMapper =
        pageElements -> pageElements.stream()
                                    .map(resourceMapper)
                                    .map(ctpClient::execute)
                                    .map(CompletionStage::toCompletableFuture);

    CtpQueryUtils.queryAll(ctpClient, queryRequestSupplier.get(), pageMapper)
                 .thenApply(list -> list.stream().flatMap(Function.identity()))
                 .thenApply(stream -> stream.toArray(CompletableFuture[]::new))
                 .thenCompose(CompletableFuture::allOf)
                 .toCompletableFuture().join();
}
 
开发者ID:commercetools,项目名称:commercetools-sync-java,代码行数:28,代码来源:ITUtils.java

示例6: mapCases

import java.util.function.Supplier; //导入依赖的package包/类
@DataProvider(name="maps")
static Object[][] mapCases() {
    if (collections != null) {
        return collections;
    }

    List<Object[]> cases = new ArrayList<>();
    for (int size : new int[] {1, 2, 16}) {
        cases.add(new Object[] {
                String.format("new HashMap(%d)", size),
                (Supplier<Map<Integer, Integer>>)
                () -> Collections.unmodifiableMap(fillMap(size, new HashMap<>())) });
        cases.add(new Object[] {
                String.format("new TreeMap(%d)", size),
                (Supplier<Map<Integer, Integer>>)
                () -> Collections.unmodifiableSortedMap(fillMap(size, new TreeMap<>())) });
    }

    return cases.toArray(new Object[0][]);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:UnmodifiableMapEntrySet.java

示例7: registerItem

import java.util.function.Supplier; //导入依赖的package包/类
@Override
protected void registerItem(EndpointsEntry entry, MethodSpec.Builder methodBuilder) {
    final FullClassName handlerEndpoint = new FullClassName(entry.element.fullQualifiedNoneGenericName() + "EndpointHandler");
    String path = entry.element.getAnnotation(Handler.class).value();

    ClassName handlerEndpointType = ClassName.get(handlerEndpoint.asPackage(), handlerEndpoint.asSimpleName());
    MethodSpec getMethod = MethodSpec.methodBuilder("get")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(handlerEndpointType)
            .addStatement("return new $T()", handlerEndpointType)
            .build();

    TypeSpec factoryType = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName.get(ClassName.get(Supplier.class), handlerEndpointType.box()))
            .addMethod(getMethod)
            .build();
    methodBuilder.addStatement("registry.registerEndpoint(\"" + path + "\", $L)", factoryType);
}
 
开发者ID:GwtDomino,项目名称:domino,代码行数:20,代码来源:EndpointsRegisterMethodWriter.java

示例8: testSubNetworkInterfaces

import java.util.function.Supplier; //导入依赖的package包/类
@Test
public void testSubNetworkInterfaces() throws SocketException {
    Supplier<Stream<NetworkInterface>> ss = () -> {
        try {
            return allNetworkInterfaces();
        }
        catch (SocketException e) {
            throw new RuntimeException(e);
        }
    };

    Collection<NetworkInterface> expected = getAllNetworkInterfaces();
    withData(TestData.Factory.ofSupplier("All network interfaces", ss))
            .stream(s -> s)
            .expectedResult(expected)
            .exercise();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:NetworkInterfaceStreamTest.java

示例9: testNetworkInterfaces

import java.util.function.Supplier; //导入依赖的package包/类
@Test
public void testNetworkInterfaces() throws SocketException {
    Supplier<Stream<NetworkInterface>> ss = () -> {
        try {
            return NetworkInterface.networkInterfaces()
                    .filter(ni -> isIncluded(ni));
        }
        catch (SocketException e) {
            throw new RuntimeException(e);
        }
    };

    Collection<NetworkInterface> enums = Collections.list(NetworkInterface.getNetworkInterfaces());
    Collection<NetworkInterface> expected = new ArrayList<>();
    enums.forEach(ni -> {
        if (isIncluded(ni)) {
            expected.add(ni);
        }
    });
    withData(TestData.Factory.ofSupplier("Top-level network interfaces", ss))
            .stream(s -> s)
            .expectedResult(expected)
            .exercise();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:NetworkInterfaceStreamTest.java

示例10: testMismatchingUsedVariablesAndVariableDefinitions

import java.util.function.Supplier; //导入依赖的package包/类
@Test(expected = IllegalStateException.class)
public void testMismatchingUsedVariablesAndVariableDefinitions() {
  Supplier<InputStream> sourceFile = () -> SmtEncoderTest.class.getResourceAsStream(
      "spec_freevariable.xml");

  ValidSpecification spec = TestUtils.importValidSpec(sourceFile.get(), new TypeEnum(
      "Color",
      Arrays.asList("red", "green", "blue")));
  List<ValidFreeVariable> freeVariables = TestUtils.importValidFreeVariables(sourceFile.get(),
      new TypeEnum("Color",
          Arrays.asList("red", "green", "blue")));

  int maxDuration = 5;


  SmtEncoder smtEncoder = new SmtEncoder(maxDuration, spec, Collections.emptyList());
  SmtModel output = smtEncoder.getConstraint();
  List<SExpression> constraints = output.getGlobalConstraints();
  Collection<SExpression> definitions = output.getVariableDefinitions();



}
 
开发者ID:VerifAPS,项目名称:stvs,代码行数:24,代码来源:SmtEncoderTest.java

示例11: buildRefreshModelChain

import java.util.function.Supplier; //导入依赖的package包/类
private void buildRefreshModelChain() {
    Supplier<Set<StackData>> stacksSupplier = new DataSourceStacksSupplier(commonDaoFacade, appName);
    TaskFactory taskFactory = new TaskFactory(DataSource.DATA_STORE);

    refreshModelChain = new TaskChain( new InitDataStoreTask(modelFacade))
        .and(taskFactory.newGetFlavorRules())
        .and(taskFactory.newGetUrlRules())
        .and(taskFactory.newGetWhitelistedStacks())
        .and(taskFactory.newGetNamespacedLists())
        .and(taskFactory.newGetStacksWithHostsTask(stacksSupplier))
        .and(taskFactory.newBackupStacksInMemory())
        .and(taskFactory.newValidateAbleToRedirectTask())
        .and(taskFactory.newApplyNewModelTask());

    if (isStaticDiscoveryNeededForApp.test(appName)) {
        refreshModelChain.and(new TriggerManualBackupTask(stacksBackupManager));
    }

    refreshModelChain.and(new BackupNewModelTask(flavorRulesHolder, whiteListHolder, urlRulesHolder, modelMetadataHolder));
}
 
开发者ID:Comcast,项目名称:redirector,代码行数:21,代码来源:RedirectorEngineProvider.java

示例12: allStringJoins

import java.util.function.Supplier; //导入依赖的package包/类
@Test
public void allStringJoins() {
    List<Supplier<Refactor.LongTrackFinder>> finders = Arrays.<Supplier<Refactor.LongTrackFinder>>asList(
        Refactor.Step0::new,
        Refactor.Step1::new,
        Refactor.Step2::new,
        Refactor.Step3::new,
        Refactor.Step4::new
    );

    List<Album> albums = unmodifiableList(asList(SampleData.aLoveSupreme, SampleData.sampleShortAlbum));
    List<Album> noTracks = unmodifiableList(asList(SampleData.sampleShortAlbum));

    finders.forEach(finder -> {
        System.out.println("Testing: " + finder.toString());

        Refactor.LongTrackFinder longTrackFinder = finder.get();
        Set<String> longTracks = longTrackFinder.findLongTracks(albums);

        assertEquals("[Acknowledgement, Resolution]", longTracks.toString());

        longTracks = longTrackFinder.findLongTracks(noTracks);

        assertTrue(longTracks.isEmpty());
    });
}
 
开发者ID:jinyi233,项目名称:https-github.com-RichardWarburton-java-8-Lambdas-exercises,代码行数:27,代码来源:RefactorTest.java

示例13: testUnawaitedBackgroundWorkShouldCompleteWithoutSyncBlock

import java.util.function.Supplier; //导入依赖的package包/类
@Test
public void testUnawaitedBackgroundWorkShouldCompleteWithoutSyncBlock() throws Exception {
	CompletableFuture<Void> unawaitedWorkCompleted = new CompletableFuture<>();
	Supplier<CompletableFuture<Void>> otherAsyncMethod = ExecutionContext.wrap(() -> {
		StrongBox<CompletableFuture<Void>> result = new StrongBox<>();
		Consumer<Void> implementation = ignored -> result.value = Async.awaitAsync(
			// this posts to the JoinableTask.threadPoolQueue
			Async.yieldAsync(),
			() -> Async.awaitAsync(
				// this should schedule directly to the .NET ThreadPool.
				Async.yieldAsync(),
				() -> {
					unawaitedWorkCompleted.complete(null);
					return Futures.completedNull();
				}));

		ExecutionContext.run(ExecutionContext.capture(), implementation, null);
		return result.value;
	});

	CompletableFuture<Void> bkgrndThread = Futures.runAsync(() -> {
		asyncPump.run(() -> {
			TplExtensions.forget(otherAsyncMethod.get());
			return Futures.completedNull();
		});
	});

	bkgrndThread.join();
	unawaitedWorkCompleted.get(EXPECTED_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
}
 
开发者ID:tunnelvisionlabs,项目名称:java-threading,代码行数:31,代码来源:JoinableFutureTest.java

示例14: maybeAssignManifoldType

import java.util.function.Supplier; //导入依赖的package包/类
@Override
public void maybeAssignManifoldType( ClassLoader loader, String fqn, URL url, BiConsumer<String, Supplier<byte[]>> assigner )
{
  Set<ITypeManifold> sps = getCurrentModule().findTypeManifoldsFor( fqn );
  if( !sps.isEmpty() )
  {
    assigner.accept( fqn, null );
  }
}
 
开发者ID:manifold-systems,项目名称:manifold,代码行数:10,代码来源:DefaultManifoldHost.java

示例15: delayedException

import java.util.function.Supplier; //导入依赖的package包/类
protected <T> CompletableFuture<T> delayedException (final long delay, final Supplier<Exception> exceptionSupplier) {
    final CompletableFuture<T> future = new CompletableFuture<>();
    rule.vertx().setTimer(delay, l -> rule.vertx().runOnContext(v -> {
        future.completeExceptionally(exceptionSupplier.get());
    }));
    return future;
}
 
开发者ID:millross,项目名称:pac4j-async,代码行数:8,代码来源:VertxAsyncTestBase.java


注:本文中的java.util.function.Supplier类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。