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


Java Consumer类代码示例

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


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

示例1: showAndWait

import java.util.function.Consumer; //导入依赖的package包/类
public static void showAndWait(String url, 
        Predicate<WebEngine> loginSuccessTest,
        Consumer<WebEngine> handler) {
    try {
        FXMLLoader loader = new FXMLLoader(LoginController.class.getResource("/fxml/login.fxml"));

        Stage stage = new Stage();
        stage.setScene(new Scene(loader.load()));
        LoginController controller = loader.<LoginController>getController();
        controller.setUrl(url);
        controller.setLoginSuccessTest(loginSuccessTest);
        controller.setHandler(handler);

        stage.setTitle("Login...");
        stage.initModality(Modality.APPLICATION_MODAL);

        stage.showAndWait();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Programming-Blueprints,代码行数:22,代码来源:LoginController.java

示例2: onCommand

import java.util.function.Consumer; //导入依赖的package包/类
@Override
public boolean onCommand(Message message, String[] args) {
    if (args.length == 0) {
        return sendErrorMessage(message, "Missing argument `ip`, you must include a valid IP address.");
    }

    if (!urlRegEX.matcher(args[0]).find()) {
        return sendErrorMessage(message, "Invalid IP address given, you must parse a valid IP address.");
    }

    RequestFactory.makeGET("http://ipinfo.io/" + args[0] + "/json").send((Consumer<Response>) response -> {
        JSONObject json = new JSONObject(response.toString());

        MessageFactory.makeEmbeddedMessage(message.getChannel(), Color.decode("#005A8C"),
            new MessageEmbed.Field("Hostname", json.has("hostname") ? json.getString("hostname") : "Unknown", true),
            new MessageEmbed.Field("Organisation", json.has("org") ? json.getString("org") : "Unknown", true),
            new MessageEmbed.Field("Country", generateLocation(json), false)
        ).setTitle(args[0]).setFooter(generateFooter(message), null).queue();
    });

    return true;
}
 
开发者ID:avaire,项目名称:avaire,代码行数:23,代码来源:IPInfoCommand.java

示例3: testSplitAfterFullTraversal

import java.util.function.Consumer; //导入依赖的package包/类
private static <T, S extends Spliterator<T>> void testSplitAfterFullTraversal(
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    // Full traversal using tryAdvance
    Spliterator<T> spliterator = supplier.get();
    while (spliterator.tryAdvance(boxingAdapter.apply(e -> { }))) { }
    Spliterator<T> split = spliterator.trySplit();
    assertNull(split);

    // Full traversal using forEach
    spliterator = supplier.get();
    spliterator.forEachRemaining(boxingAdapter.apply(e -> {
    }));
    split = spliterator.trySplit();
    assertNull(split);

    // Full traversal using tryAdvance then forEach
    spliterator = supplier.get();
    spliterator.tryAdvance(boxingAdapter.apply(e -> { }));
    spliterator.forEachRemaining(boxingAdapter.apply(e -> {
    }));
    split = spliterator.trySplit();
    assertNull(split);
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:25,代码来源:SpliteratorCollisions.java

示例4: update

import java.util.function.Consumer; //导入依赖的package包/类
/**
 * Creates context for update operation.
 * @param srcRoot the root
 * @param isCopyResources true for resource update
 * @param cacheRoot the cache root
 * @param updated the changed files
 * @param deleted the deleted files
 * @param firer the fire callback
 * @return the {@link Context} for update operation
 */
@NonNull
public static Context update(
        @NonNull final URL srcRoot,
        final boolean isCopyResources,
        @NonNull final File cacheRoot,
        @NonNull final Iterable<? extends File> updated,
        @NonNull final Iterable<? extends File> deleted,
        @NullAllowed final Consumer<Iterable<File>> firer) {
    Parameters.notNull("srcRoot", srcRoot); //NOI18N
    Parameters.notNull("cacheRoot", cacheRoot); //NOI18N
    Parameters.notNull("updated", updated); //NOI18N
    Parameters.notNull("deleted", deleted); //NOI18N            
    return new Context(
            Operation.UPDATE, srcRoot, isCopyResources, false, cacheRoot, updated, deleted, null, firer);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:26,代码来源:CompileOnSaveAction.java

示例5: test

import java.util.function.Consumer; //导入依赖的package包/类
static void test(String algo, Provider provider, boolean priv,
        Consumer<Key> method) throws Exception {
    KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance(algo, provider);
    } catch (NoSuchAlgorithmException nsae) {
        return;
    }

    System.out.println("Checking " + provider.getName() + ", " + algo);

    KeyPair pair = generator.generateKeyPair();
    Key key = priv ? pair.getPrivate() : pair.getPublic();

    pair = null;
    for (int i = 0; i < 32; ++i) {
        System.gc();
    }

    try {
        method.accept(key);
    } catch (ProviderException pe) {
        failures++;
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:26,代码来源:FinalizeHalf.java

示例6: visitGeometry

import java.util.function.Consumer; //导入依赖的package包/类
/**
 * Visit all geometries.
 *
 * @param spatial  the spatial
 * @param consumer the consumer
 */
public static void visitGeometry(@NotNull final Spatial spatial, @NotNull final Consumer<Geometry> consumer) {

    if (spatial instanceof Geometry) {
        consumer.accept((Geometry) spatial);
        return;
    } else if (!(spatial instanceof Node)) {
        return;
    }

    final Node node = (Node) spatial;

    for (final Spatial children : node.getChildren()) {
        visitGeometry(children, consumer);
    }
}
 
开发者ID:JavaSaBr,项目名称:jmonkeybuilder,代码行数:22,代码来源:NodeUtils.java

示例7: distinct

import java.util.function.Consumer; //导入依赖的package包/类
public static <T> Stream<T> distinct(Stream<T> src, Comparator<T> cmp) {
    Spliterator<T> iter = src.spliterator();
    Spliterator<T> res = new AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED ) {
        // ArrayList<T> distinctData = new ArrayList<>();
        TreeSet<T> distinctData = new TreeSet<>(cmp);
        @Override
        public boolean tryAdvance(Consumer<? super T> action) {
            return iter.tryAdvance( item -> {
                // Versão 1: if (!contains(distinctData, cmp, item)) {
                // Versão 2: if(!distinctData.stream().anyMatch(e -> cmp.compare(e, item) == 0)) {
                // Versão 3:
                if (!distinctData.contains(item)) {
                    distinctData.add(item);
                    action.accept(item);
                }
            });
        }
    };
    return StreamSupport.stream(res, false);
}
 
开发者ID:isel-leic-mpd,项目名称:mpd-2017-i41d,代码行数:21,代码来源:StreamUtils.java

示例8: assertGenerated

import java.util.function.Consumer; //导入依赖的package包/类
private static void assertGenerated(Class<?> clazz, String name, Consumer<ThriftIdlGeneratorConfig.Builder> configConsumer)
        throws IOException
{
    String expected = Resources.toString(getResource(format("expected/%s.txt", name)), UTF_8);

    ThriftIdlGeneratorConfig.Builder config = ThriftIdlGeneratorConfig.builder()
            .includes(ImmutableMap.of())
            .namespaces(ImmutableMap.of())
            .recursive(true);
    configConsumer.accept(config);

    ThriftIdlGenerator generator = new ThriftIdlGenerator(config.build());
    String idl = generator.generate(ImmutableList.of(clazz.getName()));

    assertEquals(idl, expected);
}
 
开发者ID:airlift,项目名称:drift,代码行数:17,代码来源:TestThriftIdlGenerator.java

示例9: testRetryAndSucceed

import java.util.function.Consumer; //导入依赖的package包/类
public void testRetryAndSucceed() throws Exception {
    AtomicBoolean called = new AtomicBoolean();
    Consumer<Response> checkResponse = r -> {
        assertThat(r.getFailures(), hasSize(0));
        called.set(true);
    };
    retriesAllowed = between(1, Integer.MAX_VALUE);
    sourceWithMockedRemoteCall("fail:rejection.json", "start_ok.json").doStart(checkResponse);
    assertTrue(called.get());
    assertEquals(1, retries);
    retries = 0;
    called.set(false);
    sourceWithMockedRemoteCall("fail:rejection.json", "scroll_ok.json").doStartNextScroll("scroll", timeValueMillis(0),
            checkResponse);
    assertTrue(called.get());
    assertEquals(1, retries);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:RemoteScrollableHitSourceTests.java

示例10: tryAdvance

import java.util.function.Consumer; //导入依赖的package包/类
public boolean tryAdvance(Consumer<? super V> action) {
    int hi;
    if (action == null)
        throw new NullPointerException();
    Node<K,V>[] tab = map.table;
    if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
        while (current != null || index < hi) {
            if (current == null)
                current = tab[index++];
            else {
                V v = current.value;
                current = current.next;
                action.accept(v);
                if (map.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
        }
    }
    return false;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:22,代码来源:HashMap.java

示例11: mousePressed

import java.util.function.Consumer; //导入依赖的package包/类
@Override
public void mousePressed(final MouseEvent e) {
  this.setLocation(e);
  this.setPressed(true);
  final MouseEvent wrappedEvent = this.createEvent(e);
  this.mouseListeners.forEach(listener -> listener.mousePressed(wrappedEvent));

  if (SwingUtilities.isLeftMouseButton(e)) {
    this.isLeftMouseButtonDown = true;
  }

  if (SwingUtilities.isRightMouseButton(e)) {
    this.isRightMouseButtonDown = true;
  }

  for (final Consumer<MouseEvent> cons : this.mousePressedConsumer) {
    cons.accept(wrappedEvent);
  }
}
 
开发者ID:gurkenlabs,项目名称:litiengine,代码行数:20,代码来源:Mouse.java

示例12: testCase

import java.util.function.Consumer; //导入依赖的package包/类
private void testCase(Query query, String field, int precision, CheckedConsumer<RandomIndexWriter, IOException> buildIndex,
                      Consumer<InternalGeoHashGrid> verify) throws IOException {
    Directory directory = newDirectory();
    RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory);
    buildIndex.accept(indexWriter);
    indexWriter.close();

    IndexReader indexReader = DirectoryReader.open(directory);
    IndexSearcher indexSearcher = newSearcher(indexReader, true, true);

    GeoGridAggregationBuilder aggregationBuilder = new GeoGridAggregationBuilder("_name").field(field);
    aggregationBuilder.precision(precision);
    MappedFieldType fieldType = new GeoPointFieldMapper.GeoPointFieldType();
    fieldType.setHasDocValues(true);
    fieldType.setName(FIELD_NAME);
    try (Aggregator aggregator = createAggregator(aggregationBuilder, indexSearcher, fieldType)) {
        aggregator.preCollection();
        indexSearcher.search(query, aggregator);
        aggregator.postCollection();
        verify.accept((InternalGeoHashGrid) aggregator.buildAggregation(0L));
    }
    indexReader.close();
    directory.close();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:GeoHashGridAggregatorTests.java

示例13: parse

import java.util.function.Consumer; //导入依赖的package包/类
protected void parse(Path file, Consumer<MnpParser.Number> consumer) throws IOException {
    try(Stream<String> linesStream = Files.lines(file, charset)) {
        linesStream.
            skip(skipLines).
            forEach(line -> {
                String[] data = line.split(Character.toString(delimeter));
                String subscriber = countryCode + data[0].trim();
                String title = data[1].trim();
                MnpParser.Number number = new MnpParser.Number(subscriber, title);
                try {
                    consumer.accept(number);
                } catch (Throwable t) {
                    System.err.print("Error at file: "+file+", line: "+line);
                    t.printStackTrace();
                }
            });
    }
}
 
开发者ID:chukanov,项目名称:mnp,代码行数:19,代码来源:ZniisMnpParser.java

示例14: testExecuteSuccessWithOnFailure

import java.util.function.Consumer; //导入依赖的package包/类
public void testExecuteSuccessWithOnFailure() throws Exception {
    Processor processor = mock(Processor.class);
    when(processor.getType()).thenReturn("mock_processor_type");
    when(processor.getTag()).thenReturn("mock_processor_tag");
    Processor onFailureProcessor = mock(Processor.class);
    CompoundProcessor compoundProcessor = new CompoundProcessor(false, Collections.singletonList(processor),
            Collections.singletonList(new CompoundProcessor(onFailureProcessor)));
    when(store.get("_id")).thenReturn(new Pipeline("_id", "_description", version, compoundProcessor));
    IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id");
    doThrow(new RuntimeException()).when(processor).execute(eqID("_index", "_type", "_id", Collections.emptyMap()));
    @SuppressWarnings("unchecked")
    Consumer<Exception> failureHandler = mock(Consumer.class);
    @SuppressWarnings("unchecked")
    Consumer<Boolean> completionHandler = mock(Consumer.class);
    executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler);
    verify(failureHandler, never()).accept(any(ElasticsearchException.class));
    verify(completionHandler, times(1)).accept(true);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:PipelineExecutionServiceTests.java

示例15: forEachRemaining

import java.util.function.Consumer; //导入依赖的package包/类
public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
    int i, hi, mc;
    if (action == null)
        throw new NullPointerException();
    WeakHashMap<K,V> m = map;
    WeakHashMap.Entry<K,V>[] tab = m.table;
    if ((hi = fence) < 0) {
        mc = expectedModCount = m.modCount;
        hi = fence = tab.length;
    }
    else
        mc = expectedModCount;
    if (tab.length >= hi && (i = index) >= 0 &&
        (i < (index = hi) || current != null)) {
        WeakHashMap.Entry<K,V> p = current;
        current = null; // exhaust
        do {
            if (p == null)
                p = tab[i++];
            else {
                Object x = p.get();
                V v = p.value;
                p = p.next;
                if (x != null) {
                    @SuppressWarnings("unchecked") K k =
                        (K) WeakHashMap.unmaskNull(x);
                    action.accept
                        (new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
                }
            }
        } while (p != null || i < hi);
    }
    if (m.modCount != mc)
        throw new ConcurrentModificationException();
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:36,代码来源:WeakHashMap.java


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