下面列出了java.util.stream.Stream#forEach ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
}
@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));
}
@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());
}
}
}
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(""));
});
}
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");
}
);
}
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);
}
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;
}
/**
* 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();
}
});
}
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);
}
public void add(Stream<Alert> alerts) {
alerts.forEach(this::add);
}
@Override
public void addAll(final Stream<? extends T> items) {
checkNotNull(items);
items.forEach(this::add);
}
@Override
public void deleteAll(Stream<Object> ids) {
ids.forEach(this::deleteById);
}
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));
}
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;
}
/**
* 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();
}
/**
* Excludes the given variables from this combiner.
*/
public TupleCombinerBuilder exclude( Stream<String> varNamePatterns)
{
varNamePatterns.forEach( varNamePattern -> tupleCombiner_.addExcludedVar( varNamePattern));
return this;
}
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;
}
public static BooleanColumn create(String name, Stream<Boolean> stream) {
BooleanColumn column = create(name);
stream.forEach(column::append);
return column;
}
default B withOutput(Stream<ProcessOutputDescription> outputs) {
outputs.forEach(this::withOutput);
return self();
}
@SuppressWarnings("unchecked")
private void collect(ConsumerRecords consumerRecords) {
Stream<ConsumerRecord> stream = StreamSupport.stream(consumerRecords.spliterator(), false);
stream.forEach(record -> record(record.topic().toLowerCase(), false, record));
}