Java Code Examples for java.util.stream.Stream#forEach()
The following examples show how to use
java.util.stream.Stream#forEach() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HOCONFactionStorage.java From EagleFactions with MIT License | 6 votes |
private void loadFactionsConfigurationLoaders() { try { final Stream<Path> pathsStream = Files.list(this.factionsDir); pathsStream.forEach(path -> { final String factionFileName = path.getFileName().toString().toLowerCase(); final HoconConfigurationLoader configurationLoader = HoconConfigurationLoader.builder().setDefaultOptions(ConfigurateHelper.getDefaultOptions()).setPath(this.factionsDir.resolve(path)).build(); factionLoaders.put(factionFileName, configurationLoader); }); } catch (final IOException e) { e.printStackTrace(); } }
Example 2
Source File: PushableStreamTest.java From cyclops with Apache License 2.0 | 6 votes |
@Test public void testMultiple() { MultipleStreamSource<Integer> multi = StreamSource .ofMultiple(); FutureStream<Integer> pushable = multi .futureStream(new LazyReact()); ReactiveSeq<Integer> seq = multi.reactiveSeq(); Stream<Integer> stream = multi.stream(); multi.getInput().offer(100); multi.getInput().close(); Set<Integer> vals = new TreeSet<>(); pushable.forEach(vals::add); seq.forEach(vals::add); stream.forEach(vals::add); assertThat(Sets.newSet(100),is(vals)); }
Example 3
Source File: EnumerateProcessDemo.java From Java-11-Cookbook-Second-Edition with MIT License | 5 votes |
public static void main(String[] args) throws Exception{ Stream<ProcessHandle> liveProcesses = ProcessHandle.allProcesses(); liveProcesses.forEach(ph -> { ProcessHandle.Info phInfo = ph.info(); System.out.println(phInfo.command().orElse("") +" " + phInfo.user().orElse("")); }); }
Example 4
Source File: VirtualRouter.java From batfish with Apache License 2.0 | 5 votes |
private void enqueueCrossVrfRoutes( @Nonnull CrossVrfEdgeId remoteVrfToOurRib, @Nonnull Stream<RouteAdvertisement<AnnotatedRoute<AbstractRoute>>> routeAdverts, @Nullable String policyName) { if (!_crossVrfIncomingRoutes.containsKey(remoteVrfToOurRib)) { // We either messed up royally or https://github.com/batfish/batfish/issues/3050 return; } Stream<RouteAdvertisement<AnnotatedRoute<AbstractRoute>>> filteredRoutes = routeAdverts; if (policyName != null) { RoutingPolicy policy = _c.getRoutingPolicies().get(policyName); filteredRoutes = routeAdverts .map( ra -> { AnnotatedRoute<AbstractRoute> annotatedRoute = ra.getRoute(); AbstractRouteBuilder<?, ?> routeBuilder = annotatedRoute.getRoute().toBuilder(); if (policy.process(annotatedRoute, routeBuilder, IN)) { // Preserve original route's source VRF return ra.toBuilder() .setRoute( new AnnotatedRoute<>( routeBuilder.build(), annotatedRoute.getSourceVrf())) .build(); } return null; }) .filter(Objects::nonNull); } Queue<RouteAdvertisement<AnnotatedRoute<AbstractRoute>>> queue = _crossVrfIncomingRoutes.get(remoteVrfToOurRib); filteredRoutes.forEach(queue::add); }
Example 5
Source File: Dat2WordsConverter.java From THULAC-Java with MIT License | 5 votes |
/** * Convert a stream of {@link Dat} files specified by {@code datFiles} to words plus * line numbers using {@link #convertAndSave(String, boolean)} and then sort the * lines using {@link #sortAndSave(String)}. This method output messages to {@link * System#out} while executing. * * @param datFiles * The stream of {@link Dat} files, for each {@link String} in {@code datFiles}, * for example, {@code "example"}, the input {@link Dat} file is at {@code * models/example.dat}, the converted file is at {@code * build/tmp/tests/example_text.txt}, and the sorted file is at {@code * build/tmp/tests/example_sorted.txt}. */ private void convertAndSort(Stream<String> datFiles) { datFiles.forEach(datFile -> { try { System.out.printf("Converting dat file %s.dat\n", datFile); convertAndSave(datFile, true); System.out.printf("Sorting dat file build/tmp/tests/%s_text.dat\n", datFile); sortAndSave(datFile); } catch (IOException e) { e.printStackTrace(); } }); }
Example 6
Source File: WorldHeatMapTest.java From charts with Apache License 2.0 | 5 votes |
private List<Point> readCitiesFromFile() throws IOException, URISyntaxException { List<Point> cities = new ArrayList<>(8092); URI citiesFile = (WorldHeatMapTest.class.getResource("cities.txt")).toURI(); Stream<String> lines = Files.lines(Paths.get(citiesFile)); lines.forEach(line -> { String city[] = line.split(","); double[] xy = World.latLonToXY(Double.parseDouble(city[1]), Double.parseDouble(city[2])); cities.add(new Point(xy[0], xy[1])); }); lines.close(); return cities; }
Example 7
Source File: PropertyVisitorsSequence.java From hesperides with GNU General Public License v3.0 | 5 votes |
public PropertyVisitorsSequence addValuedPropertiesIfUndefined(Stream<ValuedPropertyView> extraProperties) { Map<String, Integer> indexPerPropertyName = buildIndexPerPropertyName(); List<PropertyVisitor> newProperties = new ArrayList<>(properties); extraProperties.forEach(valuedProperty -> { Integer matchingPropertyIndex = indexPerPropertyName.get(valuedProperty.getName()); if (matchingPropertyIndex == null) { newProperties.add(new SimplePropertyVisitor(valuedProperty)); } }); return new PropertyVisitorsSequence(newProperties); }
Example 8
Source File: Pom.java From CrossMobile with GNU Lesser General Public License v3.0 | 5 votes |
private void updateDependencies(XMLWalker walker, Stream<Dependency> dependencies, String profile, boolean plugin, Predicate<XMLWalker> deletePredicate) { walker.tag("deproot") .execIf(n -> n.nodeExists("dependency"), n -> n.nodes("dependency", d -> d.execIf(deletePredicate, XMLWalker::remove))); dependencies.forEach(d -> { walker.toTag("deproot").add("dependency").tag("dep"); updateDependenciesNode(walker.toTag("dep"), "groupId", d.groupId); updateDependenciesNode(walker.toTag("dep"), "artifactId", plugin ? d.artifactId : d.profileArtifactId(profile)); updateDependenciesNode(walker.toTag("dep"), "version", d.version.equals(Version.VERSION) ? "${crossmobile.version}" : d.version); updateDependenciesNode(walker.toTag("dep"), "classifier", d.classifier); updateDependenciesNode(walker.toTag("dep"), "packaging", d.packaging == null || d.packaging.equals("jar") ? null : d.packaging); updateDependenciesNode(walker.toTag("dep"), "scope", plugin ? d.scope : profile == null ? "provided" : "runtime"); } ); }
Example 9
Source File: BulkInputCallerTest.java From java-client-api with Apache License 2.0 | 5 votes |
@Test public void bulkInputEndpointTest() { String apiName = "bulkInputCallerImpl.api"; String endpointState = "{\"next\":"+startValue+"}"; String workUnit = "{\"max\":"+workMax+"}"; InputEndpoint loadEndpt = InputEndpoint.on(IOTestUtil.db, new JacksonHandle(apiObj)); InputEndpoint.BulkInputCaller loader = loadEndpt.bulkCaller(); loader.setEndpointState(new ByteArrayInputStream(endpointState.getBytes())); loader.setWorkUnit(new ByteArrayInputStream(workUnit.getBytes())); Stream<InputStream> input = Stream.of( IOTestUtil.asInputStream("{\"docNum\":1, \"docName\":\"doc1\"}"), IOTestUtil.asInputStream("{\"docNum\":2, \"docName\":\"doc2\"}"), IOTestUtil.asInputStream("{\"docNum\":3, \"docName\":\"doc3\"}") ); input.forEach(loader::accept); loader.awaitCompletion(); for (int startNext=startValue; startNext < workMax; startNext++) { int endNext=startNext+1; String uri = "/marklogic/ds/test/bulkInputCaller/"+endNext+".json"; JsonNode doc = docMgr.read(uri, new JacksonHandle()).get(); assertNotNull("Could not find file "+uri, doc); assertEquals("state mismatch", endNext, doc.get("state").get("next").asInt()); assertEquals("state mismatch", workMax, doc.get("work").get("max").asInt()); JsonNode inputs = doc.get("inputs"); int docCount = (endNext == workMax) ? 1 : 2; assertEquals("inputs mismatch", docCount, inputs.size()); for (int j=0; j < docCount; j++) { int offset = j + (startNext * 2) - 1; JsonNode inputDoc = inputs.get(j); assertEquals("docNum mismatch", offset, inputDoc.get("docNum").asInt()); assertEquals("docName mismatch", "doc"+offset, inputDoc.get("docName").asText()); } } }
Example 10
Source File: MetricsRequestHandler.java From smallrye-metrics with Apache License 2.0 | 4 votes |
/** * Find the best matching media type (i.e. the one with highest prio. * If two have the same prio, and one is text/plain, then use this. * Return empty if no match can be found * * @param acceptHeaders A steam of Accept: headers * @return best media type as string or null if no match */ // This should be available somewhere in http handling world Optional<String> getBestMatchingMediaType(Stream<String> acceptHeaders) { List<WTTuple> tupleList = new ArrayList<>(); // Dissect the heades into type and prio and put them in a list acceptHeaders.forEach(h -> { String[] headers = h.split(","); for (String header : headers) { String[] parts = header.split(";"); float prio = 1.0f; if (parts.length > 1) { for (String x : parts) { if (x.startsWith("q=")) { prio = Float.parseFloat(x.substring(2)); } } } WTTuple t = new WTTuple(prio, parts[0]); tupleList.add(t); } }); WTTuple bestMatchTuple = new WTTuple(-1, null); // Iterate over the list and find the best match for (WTTuple tuple : tupleList) { if (!isKnownMediaType(tuple)) { continue; } if (tuple.weight > bestMatchTuple.weight) { bestMatchTuple = tuple; } else if (tuple.weight == bestMatchTuple.weight) { if (!bestMatchTuple.type.equals(TEXT_PLAIN) && tuple.type.equals(TEXT_PLAIN)) { bestMatchTuple = tuple; } } } // We found a match. Now if this is */* return text/plain. Otherwise return the type found if (bestMatchTuple.weight > 0) { return bestMatchTuple.type.equals(STAR_STAR) ? Optional.of(TEXT_PLAIN) : Optional.of(bestMatchTuple.type); } // No match return Optional.empty(); }
Example 11
Source File: TupleCombinerBuilder.java From tcases with MIT License | 4 votes |
/** * Excludes the given variables from this combiner. */ public TupleCombinerBuilder exclude( Stream<String> varNamePatterns) { varNamePatterns.forEach( varNamePattern -> tupleCombiner_.addExcludedVar( varNamePattern)); return this; }
Example 12
Source File: AlertCollector.java From sailfish-core with Apache License 2.0 | 4 votes |
public void add(Stream<Alert> alerts) { alerts.forEach(this::add); }
Example 13
Source File: TofuNetwork.java From TofuCraftReload with MIT License | 4 votes |
public static List<String> toUUIDs(Stream<Map.Entry<String, TileEntity>> map) { List<String> uids = new ArrayList<>(); map.forEach(entry -> uids.add(entry.getKey())); return uids; }
Example 14
Source File: ConceptManagerImpl.java From grakn with GNU Affero General Public License v3.0 | 4 votes |
public Set<Concept> getConcepts(Schema.VertexProperty key, Object value) { Set<Concept> concepts = new HashSet<>(); Stream<VertexElement> vertices = elementFactory.getVerticesWithProperty(key, value); vertices.forEach(vertexElement -> concepts.add(buildConcept(vertexElement))); return concepts; }
Example 15
Source File: BooleanColumn.java From tablesaw with Apache License 2.0 | 4 votes |
public static BooleanColumn create(String name, Stream<Boolean> stream) { BooleanColumn column = create(name); stream.forEach(column::append); return column; }
Example 16
Source File: ProcessOutputDescriptionContainer.java From arctic-sea with Apache License 2.0 | 4 votes |
default B withOutput(Stream<ProcessOutputDescription> outputs) { outputs.forEach(this::withOutput); return self(); }
Example 17
Source File: SampleModelStreamTest.java From doov with Apache License 2.0 | 4 votes |
private static void should_peek_fields_values_when_using_stream(Stream<Entry<FieldId, Object>> stream) { Set<FieldId> peeked = newSetFromMap(new ConcurrentHashMap<>()); stream.forEach(e -> peeked.add(e.getKey())); assertThat(peeked).containsAll(EnumSet.allOf(SampleFieldId.class)); }
Example 18
Source File: InMemoryRepository.java From molgenis with GNU Lesser General Public License v3.0 | 4 votes |
@Override public void deleteAll(Stream<Object> ids) { ids.forEach(this::deleteById); }
Example 19
Source File: ConsumerCollector.java From ksql-fork-with-deep-learning-function with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") private void collect(ConsumerRecords consumerRecords) { Stream<ConsumerRecord> stream = StreamSupport.stream(consumerRecords.spliterator(), false); stream.forEach(record -> record(record.topic().toLowerCase(), false, record)); }
Example 20
Source File: LifoWaitlist.java From theta with Apache License 2.0 | 4 votes |
@Override public void addAll(final Stream<? extends T> items) { checkNotNull(items); items.forEach(this::add); }