Java Code Examples for java.util.function.Consumer
The following are top voted examples for showing how to use
java.util.function.Consumer. These examples are extracted from open source projects.
You can vote up the examples you like and your votes will be used in our system to generate
more good examples.
Example 1
Project: Java-9-Programming-Blueprints File: LoginController.java View source code | 8 votes |
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); } }
Example 2
Project: avaire File: IPInfoCommand.java View source code | 6 votes |
@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; }
Example 3
Project: jdk8u-jdk File: SpliteratorCollisions.java View source code | 6 votes |
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); }
Example 4
Project: incubator-netbeans File: CompileOnSaveAction.java View source code | 6 votes |
/** * 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); }
Example 5
Project: jdk8u-jdk File: FinalizeHalf.java View source code | 6 votes |
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++; } }
Example 6
Project: jmonkeybuilder File: NodeUtils.java View source code | 6 votes |
/** * 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); } }
Example 7
Project: mpd-2017-i41d File: StreamUtils.java View source code | 6 votes |
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); }
Example 8
Project: drift File: TestThriftIdlGenerator.java View source code | 6 votes |
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); }
Example 9
Project: elasticsearch_my File: RemoteScrollableHitSourceTests.java View source code | 6 votes |
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); }
Example 10
Project: jdk8u-jdk File: HashMap.java View source code | 6 votes |
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; }
Example 11
Project: litiengine File: Mouse.java View source code | 6 votes |
@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); } }
Example 12
Project: elasticsearch_my File: GeoHashGridAggregatorTests.java View source code | 6 votes |
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(); }
Example 13
Project: mnp File: ZniisMnpParser.java View source code | 6 votes |
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(); } }); } }
Example 14
Project: elasticsearch_my File: PipelineExecutionServiceTests.java View source code | 6 votes |
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); }
Example 15
Project: jdk8u-jdk File: WeakHashMap.java View source code | 5 votes |
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(); }
Example 16
Project: hashsdn-controller File: LocalProxyTransactionTest.java View source code | 5 votes |
protected <R extends TransactionRequest<R>> R testForwardToLocal(final TransactionRequest<?> toForward, final Class<R> expectedMessageClass) { final Consumer<Response<?, ?>> callback = createCallbackMock(); final TransactionTester<LocalReadWriteProxyTransaction> transactionTester = createLocalProxy(); final LocalReadWriteProxyTransaction successor = transactionTester.getTransaction(); transaction.forwardToLocal(successor, toForward, callback); return transactionTester.expectTransactionRequest(expectedMessageClass); }
Example 17
Project: datarouter File: DatarouterHttpClient.java View source code | 5 votes |
public DatarouterHttpResponse execute(DatarouterHttpRequest request, Consumer<HttpEntity> httpEntityConsumer){ try{ return executeChecked(request, httpEntityConsumer); }catch(DatarouterHttpException e){ throw new DatarouterHttpRuntimeException(e); } }
Example 18
Project: mug File: Funnel.java View source code | 5 votes |
/** * Adds {@code source} to be converted. * {@code aftereffect} will be applied against the conversion result after the batch completes. */ public void accept(F source, Consumer<? super T> aftereffect) { requireNonNull(aftereffect); accept(source, v -> { aftereffect.accept(v); return v; }); }
Example 19
Project: n4js File: SubMonitorMsg.java View source code | 5 votes |
/** * Wraps a {@link SubMonitor} */ public SubMonitorMsg(SubMonitor subMonitor, Consumer<String> callbackMsg, Consumer<String> callbackErr, CheckCanceled checkCanceled) { this.subMonitor = subMonitor; this.monitor = subMonitor; this.callbackMsg = callbackMsg; this.callbackErr = callbackErr; this.checkCanceled = checkCanceled; }
Example 20
Project: jdk8u-jdk File: DateTimeParseContext.java View source code | 5 votes |
/** * Adds a Consumer<Chronology> to the list of listeners to be notified * if the Chronology changes. * @param listener a Consumer<Chronology> to be called when Chronology changes */ void addChronoChangedListener(Consumer<Chronology> listener) { if (chronoListeners == null) { chronoListeners = new ArrayList<Consumer<Chronology>>(); } chronoListeners.add(listener); }
Example 21
Project: OpenGL-Bullet-engine File: PrefixTree.java View source code | 5 votes |
void getStartMatches(String name, int start, Consumer<T> hook){ int len=name.length(),end=start+l; if(start>=len||(end>len&&name.regionMatches(start, namePart, 0, Math.min(end, len)-start))){ if(hasValue) hook.accept(value); }else if(!match(name, start)) return; for(Node node:children){ node.getStartMatches(name, end, hook); } }
Example 22
Project: openjdk-jdk10 File: GC.java View source code | 5 votes |
public Checker(Consumer<ReferenceInfo<Object[]>> weakHumongousCheck, Consumer<ReferenceInfo<Object[]>> softHumongousCheck, Consumer<ReferenceInfo<Object[]>> weakSimpleCheck, Consumer<ReferenceInfo<Object[]>> softSimpleCheck) { this.weakHumongousCheck = weakHumongousCheck; this.softHumongousCheck = softHumongousCheck; this.weakSimpleCheck = weakSimpleCheck; this.softSimpleCheck = softSimpleCheck; }
Example 23
Project: DigitRecognizer File: Stopwatch.java View source code | 5 votes |
public static void timeExecution(Runnable task, Consumer<Long> timeConsumer) { timeExecution(() -> { task.run(); return 0; }, timeConsumer); }
Example 24
Project: java-threading File: JoinableFuture.java View source code | 5 votes |
/** * Forwards a message to the ambient job and blocks on its execution. */ @Override public <T> void send(Consumer<T> callback, T state) { Requires.notNull(callback, "callback"); // Some folks unfortunately capture the SynchronizationContext from the UI thread // while this one is active. So forward it to the underlying sync context to not break those folks. // Ideally this method would throw because synchronously crossing threads is a bad idea. if (mainThreadAffinitized) { if (jobFactory.getContext().isOnMainThread()) { callback.accept(state); } else { jobFactory.getContext().getUnderlyingSynchronizationContext().send(callback, state); } } else { //#if DESKTOP // bool isThreadPoolThread = Thread.CurrentThread.IsThreadPoolThread; //#else // // On portable profile this is the best estimation we can do. // bool isThreadPoolThread = !this.jobFactory.Context.IsOnMainThread; //#endif boolean isThreadPoolThread = !jobFactory.getContext().isOnMainThread(); if (isThreadPoolThread) { callback.accept(state); } else { CompletableFuture.runAsync(ExecutionContext.wrap(() -> callback.accept(state))).join(); } } }
Example 25
Project: AlphaLibary File: SQLiteDatabase.java View source code | 5 votes |
/** * Returns a {@link ArrayList} with all values from one coloumn * * @param column the colum to get it's values from * @return an {@link ArrayList} with all values */ public void getList(String column, Consumer<List<String>> callback) { Bukkit.getScheduler().runTaskAsynchronously(AlphaLibary.getInstance(), () -> { List<String> list = new LinkedList<>(); if (api != null) { if (api.isConnected()) { try { ResultSet rs = api.getSQLiteConnection().prepareStatement("SELECT " + column + " FROM " + tableName + ";").executeQuery(); if (rs == null) { Bukkit.getScheduler().runTask(AlphaLibary.getInstance(), () -> callback.accept(list)); return; } while (rs.next()) { String str = rs.getString(column); if (str.startsWith("{") && str.endsWith("}")) list.add(str); else { if (!str.contains(", ")) { list.add(str.replace("[", "").replace("]", "")); } else { String[] strlist = str.split(", "); for (String aStrlist : strlist) { list.add(aStrlist.replace("[", "").replace("]", "")); } } } } Bukkit.getScheduler().runTask(AlphaLibary.getInstance(), () -> callback.accept(list)); return; } catch (SQLException ignored) { } } } Bukkit.getScheduler().runTask(AlphaLibary.getInstance(), () -> callback.accept(list)); }); }
Example 26
Project: com-liferay-apio-architect File: ItemRoutes.java View source code | 5 votes |
/** * Adds a route to a remover function with none extra parameters. * * @param consumer the remover function that removes the item * @return the updated builder */ public Builder<T, S> addRemover(Consumer<S> consumer) { _deleteItemConsumer = httpServletRequest -> path -> consumer.accept( _getIdentifier(path)); return this; }
Example 27
Project: avaire File: ChuckNorrisCommand.java View source code | 5 votes |
@Override public boolean onCommand(Message message, String[] args) { RequestFactory.makeGET("http://api.icndb.com/jokes/random") .addParameter("escape", "javascript") .send((Consumer<Response>) response -> { ChuckNorrisService service = (ChuckNorrisService) response.toService(ChuckNorrisService.class); MessageFactory.makeSuccess(message, prepareJoke(message, args, service.getValue().getJoke())).queue(); }); return true; }
Example 28
Project: MCLibrary File: Static.java View source code | 5 votes |
public static void getAddressAsync(Plugin plugin, Consumer<String> callback) { Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { try { BufferedReader reader = new BufferedReader(new InputStreamReader( new URL("http://checkip.amazonaws.com").openStream())); callback.accept(reader.readLine()); } catch (IOException e) { Static.log(e); } }); }
Example 29
Project: moviediary File: RestApiRxVerticle.java View source code | 5 votes |
@SafeVarargs protected final void startRestRouter(Future<Void> future, Consumer<RestRouter>... consumers) { SChain.of(config().getInteger("http.port", getRandomUnboundPort())) .toPChain(RestRouter.create(vertx)) .mapSnd(restRouter -> chain(restRouter, consumers).build()) .mapSnd((port, router) -> createHttpServer(router, port)) .mapSChain((port, single) -> single.flatMap(v -> publishHttpEndpoint(port))) .peek(single -> single.subscribe(toSubscriber(future.completer()))); /*chain(config().getInteger("http.port", getRandomUnboundPort()), port -> createHttpServer(chain(RestRouter.create(vertx), consumers).build(), port) .flatMap(v -> publishHttpEndpoint(port)) .subscribe(toSubscriber(future.completer())));*/ }
Example 30
Project: openjdk-jdk10 File: SerializedLambdaTest.java View source code | 5 votes |
public void testDiscardReturnBound() throws IOException, ClassNotFoundException { List<String> list = new ArrayList<>(); Consumer<String> c = (Consumer<String> & Serializable) list::add; assertSerial(c, cc -> { assertTrue(cc instanceof Consumer); }); AtomicLong a = new AtomicLong(); LongConsumer lc = (LongConsumer & Serializable) a::addAndGet; assertSerial(lc, plc -> { plc.accept(3); }); }
Example 31
Project: molten-json File: JsonObject.java View source code | 5 votes |
public JsonObject array(String key, Consumer<JsonArray> value) { requireNonNull(key, "JSON keys must not be null."); JSONArray jsonOrgArray = new JSONArray(); JsonArray jsonArray = new JsonArray(jsonOrgArray, nullHandlingStrategy); value.accept(jsonArray); suppress(() -> jsonOrgObject.put(key, jsonOrgArray)); return this; }
Example 32
Project: OpenJSharp File: TreeMap.java View source code | 5 votes |
public boolean tryAdvance(Consumer<? super K> action) { if (hasNext()) { action.accept(next()); return true; } return false; }
Example 33
Project: openjdk-jdk10 File: FileChannelLinesSpliterator.java View source code | 5 votes |
@Override public boolean tryAdvance(Consumer<? super String> action) { String line = readLine(); if (line != null) { action.accept(line); return true; } else { return false; } }
Example 34
Project: OpenJSharp File: StreamSpliterators.java View source code | 5 votes |
@Override public void forEachRemaining(Consumer<? super P_OUT> consumer) { if (buffer == null && !finished) { Objects.requireNonNull(consumer); init(); ph.wrapAndCopyInto((Sink<P_OUT>) consumer::accept, spliterator); finished = true; } else { do { } while (tryAdvance(consumer)); } }
Example 35
Project: MCOpts File: Expect.java View source code | 5 votes |
/** * For quoted arguments with spaces that repeat just one completion */ public Expect words(Consumer<Expect> consumer) { Expect inner = splitInner(expect -> expect.then(consumer).repeat()); descriptionU(Iterables.getLast(inner.mapLastDescriptions((i, s) -> s))); return this; }
Example 36
Project: litiengine File: MovableEntity.java View source code | 5 votes |
@Override public void onMoved(final Consumer<IMovableEntity> consumer) { if (this.entityMovedConsumer.contains(consumer)) { return; } this.entityMovedConsumer.add(consumer); }
Example 37
Project: stroom-stats File: TestLocationChecker.java View source code | 5 votes |
private void performFileActionsInEachModule(Predicate<Path> fileTest, Consumer<Path> fileAction, Path relativeSubPath) throws IOException { Consumer<Path> processModuleDir = (modulePath) -> { // System.out.println("Processing module [" + modulePath.getFileName().toString() + "]"); try { // Path srcPath = Paths.get(modulePath.toString(), "src", "main", "java"); Path srcPath = modulePath.resolve(relativeSubPath); // System.out.println("srcPath [" + srcPath + "]"); if (Files.isDirectory(srcPath)) { Files.walk(srcPath) .parallel() .filter(Files::isRegularFile) .filter(fileTest) .filter(path -> path.getFileName().toString().endsWith(".java")) .forEach(fileAction); } } catch (IOException e) { throw new RuntimeException(e); } }; Files.list(PROJECT_ROOT_PATH) .parallel() .filter(Files::isDirectory) // .filter(fileTest) .forEach(processModuleDir); }
Example 38
Project: openjdk-jdk10 File: Utils.java View source code | 5 votes |
/** * Runs runnable and makes some checks to ensure that it throws expected exception. * @param runnable what we run * @param checkException a consumer which checks that we got expected exception and raises a new exception otherwise */ public static void runAndCheckException(Runnable runnable, Consumer<Throwable> checkException) { try { runnable.run(); checkException.accept(null); } catch (Throwable t) { checkException.accept(t); } }
Example 39
Project: incubator-netbeans File: JavaActionProvider.java View source code | 5 votes |
SimpleAction( @NonNull final String name, final Consumer<? super Context> performer) { Parameters.notNull("name", name); //NOI18N Parameters.notNull("performer", performer); //NOI18N this.name = name; this.performer = performer; }
Example 40
Project: Spring-5.0-Cookbook File: EmployeeFileStreamService.java View source code | 5 votes |
public void viewDirFiles(String dirPath, String extension) throws IOException{ Consumer<String> readStr = System.out::println; Stream<Path> stream = Files.list(Paths.get(dirPath)).sequential(); stream.map(String::valueOf) .filter(path -> path.endsWith(extension)) .forEach(readStr); }