Java 类java.util.function.Consumer 实例源码
项目:Java-9-Programming-Blueprints
文件:LoginController.java
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);
}
}
项目:avaire
文件:IPInfoCommand.java
@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;
}
项目:jdk8u-jdk
文件:SpliteratorCollisions.java
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);
}
项目:incubator-netbeans
文件:CompileOnSaveAction.java
/**
* 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);
}
项目:jdk8u-jdk
文件:FinalizeHalf.java
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++;
}
}
项目:jmonkeybuilder
文件:NodeUtils.java
/**
* 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);
}
}
项目:mpd-2017-i41d
文件:StreamUtils.java
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);
}
项目:drift
文件:TestThriftIdlGenerator.java
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);
}
项目:elasticsearch_my
文件:RemoteScrollableHitSourceTests.java
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);
}
项目:jdk8u-jdk
文件:HashMap.java
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;
}
项目:litiengine
文件:Mouse.java
@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);
}
}
项目:elasticsearch_my
文件:GeoHashGridAggregatorTests.java
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();
}
项目:mnp
文件:ZniisMnpParser.java
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();
}
});
}
}
项目:elasticsearch_my
文件:PipelineExecutionServiceTests.java
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);
}
项目:jdk8u-jdk
文件:WeakHashMap.java
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();
}
项目:hashsdn-controller
文件:LocalProxyTransactionTest.java
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);
}
项目:datarouter
文件:DatarouterHttpClient.java
public DatarouterHttpResponse execute(DatarouterHttpRequest request, Consumer<HttpEntity> httpEntityConsumer){
try{
return executeChecked(request, httpEntityConsumer);
}catch(DatarouterHttpException e){
throw new DatarouterHttpRuntimeException(e);
}
}
项目:mug
文件:Funnel.java
/**
* 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;
});
}
项目:n4js
文件:SubMonitorMsg.java
/**
* 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;
}
项目:jdk8u-jdk
文件:DateTimeParseContext.java
/**
* 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);
}
项目:OpenGL-Bullet-engine
文件:PrefixTree.java
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);
}
}
项目:openjdk-jdk10
文件:GC.java
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;
}
项目:DigitRecognizer
文件:Stopwatch.java
public static void timeExecution(Runnable task, Consumer<Long> timeConsumer)
{
timeExecution(() ->
{
task.run();
return 0;
}, timeConsumer);
}
项目:java-threading
文件:JoinableFuture.java
/**
* 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();
}
}
}
项目:AlphaLibary
文件:SQLiteDatabase.java
/**
* 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));
});
}
项目:com-liferay-apio-architect
文件:ItemRoutes.java
/**
* 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;
}
项目:avaire
文件:ChuckNorrisCommand.java
@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;
}
项目:MCLibrary
文件:Static.java
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);
}
});
}
项目:moviediary
文件:RestApiRxVerticle.java
@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())));*/
}
项目:openjdk-jdk10
文件:SerializedLambdaTest.java
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); });
}
项目:molten-json
文件:JsonObject.java
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;
}
项目:OpenJSharp
文件:TreeMap.java
public boolean tryAdvance(Consumer<? super K> action) {
if (hasNext()) {
action.accept(next());
return true;
}
return false;
}
项目:openjdk-jdk10
文件:FileChannelLinesSpliterator.java
@Override
public boolean tryAdvance(Consumer<? super String> action) {
String line = readLine();
if (line != null) {
action.accept(line);
return true;
} else {
return false;
}
}
项目:OpenJSharp
文件:StreamSpliterators.java
@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));
}
}
项目:MCOpts
文件:Expect.java
/**
* 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;
}
项目:litiengine
文件:MovableEntity.java
@Override
public void onMoved(final Consumer<IMovableEntity> consumer) {
if (this.entityMovedConsumer.contains(consumer)) {
return;
}
this.entityMovedConsumer.add(consumer);
}
项目:stroom-stats
文件:TestLocationChecker.java
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);
}
项目:openjdk-jdk10
文件:Utils.java
/**
* 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);
}
}
项目:incubator-netbeans
文件:JavaActionProvider.java
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;
}
项目:Spring-5.0-Cookbook
文件:EmployeeFileStreamService.java
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);
}