java.util.stream.Stream#forEach ( )源码实例Demo

下面列出了java.util.stream.Stream#forEach ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: EagleFactions   文件: HOCONFactionStorage.java
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();
    }
}
 
源代码2 项目: cyclops   文件: PushableStreamTest.java
@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));
}
 
源代码3 项目: java-client-api   文件: BulkInputCallerTest.java
@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(""));
	});
}
 
源代码5 项目: CrossMobile   文件: Pom.java
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");
            }
    );
}
 
源代码6 项目: hesperides   文件: PropertyVisitorsSequence.java
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);
}
 
源代码7 项目: charts   文件: WorldHeatMapTest.java
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;
}
 
源代码8 项目: THULAC-Java   文件: Dat2WordsConverter.java
/**
 * 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();
		}
	});
}
 
源代码9 项目: batfish   文件: VirtualRouter.java
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);
}
 
源代码10 项目: sailfish-core   文件: AlertCollector.java
public void add(Stream<Alert> alerts) {
    alerts.forEach(this::add);
}
 
源代码11 项目: theta   文件: LifoWaitlist.java
@Override
public void addAll(final Stream<? extends T> items) {
	checkNotNull(items);
	items.forEach(this::add);
}
 
源代码12 项目: molgenis   文件: InMemoryRepository.java
@Override
public void deleteAll(Stream<Object> ids) {
  ids.forEach(this::deleteById);
}
 
源代码13 项目: doov   文件: SampleModelStreamTest.java
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));
}
 
源代码14 项目: grakn   文件: ConceptManagerImpl.java
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;
}
 
源代码15 项目: smallrye-metrics   文件: MetricsRequestHandler.java
/**
 * 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();
}
 
源代码16 项目: tcases   文件: TupleCombinerBuilder.java
/**
 * Excludes the given variables from this combiner.
 */
public TupleCombinerBuilder exclude( Stream<String> varNamePatterns)
  {
  varNamePatterns.forEach( varNamePattern -> tupleCombiner_.addExcludedVar( varNamePattern));
  return this;
  }
 
源代码17 项目: TofuCraftReload   文件: TofuNetwork.java
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;
}
 
源代码18 项目: tablesaw   文件: BooleanColumn.java
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));
}