本文整理匯總了Java中java.util.stream.Stream類的典型用法代碼示例。如果您正苦於以下問題:Java Stream類的具體用法?Java Stream怎麽用?Java Stream使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Stream類屬於java.util.stream包,在下文中一共展示了Stream類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: initJar
import java.util.stream.Stream; //導入依賴的package包/類
void initJar() throws IOException {
String testClassPath = System.getProperty("test.class.path", "");
Path jarsrc = Stream.of(testClassPath.split(File.pathSeparator))
.map(Paths::get)
.filter(e -> e.endsWith("jarsrc"))
.findAny()
.orElseThrow(() -> new InternalError("jarsrc not found"));
jarPath = Paths.get("lib.jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jarPath))) {
String[] classNames = {"Lib1.class", "Lib2.class"};
for (String cn : classNames) {
out.putNextEntry(new JarEntry("lib/" + cn));
Path libClass = jarsrc.resolve("lib").resolve(cn);
out.write(Files.readAllBytes(libClass));
}
}
}
示例2: searchDir
import java.util.stream.Stream; //導入依賴的package包/類
private Stream<File> searchDir(File dir, boolean warnOnBadDir) {
if (dir == null || !dir.exists() || !dir.isDirectory()) {
if (warnOnBadDir && dir != null) {
getLog().warn("Directory does not exist or is not a directory: " + dir);
}
return Stream.empty();
}
getLog().debug("Adding directory " + dir);
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(dir);
ds.setIncludes(includes != null && includes.length > 0 ? includes : DEFAULT_INCLUDES);
ds.setExcludes(excludes);
ds.addDefaultExcludes();
ds.setCaseSensitive(false);
ds.setFollowSymlinks(false);
ds.scan();
return Stream.of(ds.getIncludedFiles()).map(filename -> new File(dir, filename)).parallel();
}
示例3: testMapPartialNull
import java.util.stream.Stream; //導入依賴的package包/類
@Test
public void testMapPartialNull() throws Exception {
repeat(3, i -> {
Map<Object, Object> m1 = Stream.of("a" + i, "b" + i, "c" + i).collect(toMap(o -> o, o -> o + "test"));
when(rpc1.map(or(eq(singletonMap(i + 1, i)), eq(singletonMap(i + 2, i))))).thenReturn(m1);
when(rpc2.map(or(eq(singletonMap(i + 1, i)), eq(singletonMap(i + 2, i))))).thenReturn(null);
Map<Object, Object> args = new HashMap<>();
args.put(i + 1, i);
args.put(i + 2, i);
Map<Object, Object> result = client.map(args);
assertEquals(m1, result);
verify(rpc1).map(or(eq(singletonMap(i + 1, i)), eq(singletonMap(i + 2, i))));
verify(rpc2).map(or(eq(singletonMap(i + 1, i)), eq(singletonMap(i + 2, i))));
verifyNoMoreInteractions(rpc1, rpc2);
reset(rpc1, rpc2);
});
}
示例4: execute
import java.util.stream.Stream; //導入依賴的package包/類
@Override
public void execute(Tuple tuple) {
final String data = tuple.getString(0);
LOGGER.debug("Processing datapoint", data);
try {
Datapoint datapoint = MAPPER.readValue(data, Datapoint.class);
if (isUpdateRequired(datapoint)) {
addDatapoint(datapoint);
List<Object> stream = Stream.of(datapoint.getMetric(), datapoint.getTime(), datapoint.getValue(),
datapoint.getTags())
.collect(Collectors.toList());
LOGGER.debug("emit: " + stream);
collector.emit(stream);
}
} catch (IOException e) {
LOGGER.error("Failed read datapoint", e);
} finally {
collector.ack(tuple);
}
}
示例5: testPlusScalar
import java.util.stream.Stream; //導入依賴的package包/類
@Test(dataProvider = "styles")
public void testPlusScalar(DataFrameAlgebra.Lib lib, boolean parallel) {
DataFrameAlgebra.LIBRARY.set(lib);
Stream.of(int.class, long.class, double.class).forEach(type -> {
Array.of(20, 77, 95, 135, 233, 245).forEach(count -> {
final DataFrame<Integer,Integer> frame = random(120, count, parallel, type);
final DataFrame<Integer,Integer> result = frame.plus(25);
assertEquals(result, v -> {
switch (ArrayType.of(type)) {
case INTEGER: return frame.data().getInt(v.rowOrdinal(), v.colOrdinal()) + 25;
case LONG: return frame.data().getLong(v.rowOrdinal(), v.colOrdinal()) + 25;
default: return frame.data().getDouble(v.rowOrdinal(), v.colOrdinal()) + 25d;
}
});
});
});
}
示例6: getLock
import java.util.stream.Stream; //導入依賴的package包/類
@Override
public SharedInterProcessLock getLock(String application, EntityType entityType) {
if (! connector.isConnected()) {
throw new RedirectorDataSourceException("No connection to zookeeper");
}
String lockPath = Stream
.of(REDIRECTOR_ZOOKEEPER_PATH, SERVICES_PATH, application, REDIRECTOR_LOCK_PATH, entityType.getPath())
.collect(Collectors.joining(DELIMETER, DELIMETER, ""));
if (lockMap.containsKey(lockPath)) {
return lockMap.get(lockPath);
} else {
SharedInterProcessLock lock = connector.createLock(lockPath);
lockMap.put(lockPath, lock);
return lock;
}
}
示例7: verifySaveAttributeReleasePolicyAllowedAttrRulesAndFilter
import java.util.stream.Stream; //導入依賴的package包/類
@Test
public void verifySaveAttributeReleasePolicyAllowedAttrRulesAndFilter() {
final RegexRegisteredService r = new RegexRegisteredService();
r.setName("testSaveAttributeReleasePolicyAllowedAttrRulesAndFilter");
r.setServiceId(SERVICE_ID);
r.setTheme("testtheme");
r.setEvaluationOrder(1000);
r.setAccessStrategy(new DefaultRegisteredServiceAccessStrategy(true, false));
r.setProxyPolicy(new RegexMatchingRegisteredServiceProxyPolicy("https://.+"));
r.setRequiredHandlers(Stream.of("h1", "h2").collect(Collectors.toSet()));
final ReturnAllowedAttributeReleasePolicy policy = new ReturnAllowedAttributeReleasePolicy();
policy.setAllowedAttributes(Arrays.asList("1", "2", "3"));
r.setAttributeReleasePolicy(policy);
r.getAttributeReleasePolicy().setAttributeFilter(new RegisteredServiceRegexAttributeFilter("\\w+"));
final RegisteredService r2 = this.dao.save(r);
final RegisteredService r3 = this.dao.findServiceById(r2.getId());
assertEquals(r, r2);
assertEquals(r2, r3);
assertNotNull(r3.getAttributeReleasePolicy());
assertEquals(r2.getAttributeReleasePolicy(), r3.getAttributeReleasePolicy());
}
示例8: mirror
import java.util.stream.Stream; //導入依賴的package包/類
public QuadBuilder mirror() {
if(facingMap.containsKey(last)) {
Stream<Vector3> stream = Arrays.stream(facingMap.get(last).getVectors());
switch(last) {
case DOWN:
case UP:
stream.forEach(vec -> {
vec.subtract(0.5D).rotate(EnumFacing.Axis.Y, 180).add(0.5D);
});
break;
case NORTH:
case SOUTH:
stream.forEach(vec -> {
vec.subtract(0.5D).rotate(EnumFacing.Axis.X, 180).add(0.5D);
});
break;
case EAST:
case WEST:
stream.forEach(vec -> {
vec.subtract(0.5D).rotate(EnumFacing.Axis.Z, 180).add(0.5D);
});
break;
}
}
return this;
}
示例9: findsAllTheBeatles
import java.util.stream.Stream; //導入依賴的package包/類
@Test
public void findsAllTheBeatles() {
PerformanceFixed stub = new PerformanceFixed() {
@Override
public String getName() {
throw new UnsupportedOperationException();
}
@Override
public Stream<Artist> getMusicians() {
return Stream.of(SampleData.theBeatles);
}
};
List<Artist> allMusicians = stub.getAllMusicians().collect(toList());
assertThat(allMusicians, hasItem(SampleData.theBeatles));
// There really must be a better way than this
assertThat(allMusicians, hasItems(SampleData.membersOfTheBeatles.toArray(new Artist[0])));
}
開發者ID:jinyi233,項目名稱:https-github.com-RichardWarburton-java-8-Lambdas-exercises,代碼行數:20,代碼來源:PerformanceTest.java
示例10:
import java.util.stream.Stream; //導入依賴的package包/類
@Test
public void should_create_the_correct_stream_on_groupingBy_then_all_max_by_value_and_a_comparator_for_an_empty_stream() {
// Given
Stream<String> strings = Stream.empty();
Collector<String, ?, Set<Map.Entry<String, Long>>> collector =
CollectorsUtils.groupingByAndAllMaxByValue(
Function.<String>identity(),
counting(),
Comparator.reverseOrder()
);
// When
Set<Map.Entry<String, Long>> result = strings.collect(collector);
// Then
assertThat(result).isEmpty();
}
示例11: getLabels
import java.util.stream.Stream; //導入依賴的package包/類
private List<Label> getLabels(final Description result) {
return Stream.of(
getLabels(result, Epic.class, ResultsUtils::createLabel),
getLabels(result, Feature.class, ResultsUtils::createLabel),
getLabels(result, Story.class, ResultsUtils::createLabel),
getLabels(result, Severity.class, ResultsUtils::createLabel),
getLabels(result, Owner.class, ResultsUtils::createLabel),
getLabels(result, Tag.class, this::createLabel)
).reduce(Stream::concat).orElseGet(Stream::empty).collect(Collectors.toList());
}
示例12: canCollectPairsIntoMap
import java.util.stream.Stream; //導入依賴的package包/類
@Test
public void canCollectPairsIntoMap() {
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("hello", "world");
expectedMap.put("six of one", "half a dozen of the other");
Map<String, String> actualMap = Stream.of(
entry("hello", "world"),
entry("six of one", "half a dozen of the other")
).collect(toMap());
assertThat(actualMap, is(expectedMap));
}
示例13: testToImmutableTableMergingNullColumnKey
import java.util.stream.Stream; //導入依賴的package包/類
public void testToImmutableTableMergingNullColumnKey() {
Collector<Cell<String, String, Integer>, ?, ImmutableTable<String, String, Integer>> collector =
ImmutableTable.toImmutableTable(Cell::getRowKey, t -> null, Cell::getValue, Integer::sum);
try {
Stream.of(Tables.immutableCell("one", "uno", 1)).collect(collector);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
}
}
示例14: checkInjectedContext
import java.util.stream.Stream; //導入依賴的package包/類
private <A extends Annotation> void checkInjectedContext(InjectionDevice device, Class<A> annotationClass, boolean includeCommonContext, Class<?>... expectedContextClasses) {
Set<Object> injectedContext = device.getMethodContext(annotationClass);
assertNotNull(injectedContext);
// stream the total set of expected classes, filter out those found in context - if the resulting stream isn't empty we're missing something
final Predicate<Class<?>> contextHasInstance = klass -> injectedContext.stream().anyMatch(obj -> klass.isInstance(obj));
Stream<Class<?>> expectedClassStream = Arrays.stream(expectedContextClasses);
if (includeCommonContext) {
expectedClassStream = Stream.concat(expectedClassStream, Arrays.stream(COMMON_CONTEXT_CLASSES));
}
Optional<Class<?>> missingExpectedContext = expectedClassStream.filter(klass -> !contextHasInstance.test(klass)).findFirst();
if (missingExpectedContext.isPresent()) {
Assert.fail("Context missing expected instance of: " + missingExpectedContext.get());
}
}
示例15: dumpResults
import java.util.stream.Stream; //導入依賴的package包/類
static Stream<String> dumpResults(
Stream<Map.Entry<int[], Map<String, String>>> results
) {
return results
.map(le ->
IntStream.of(le.getKey())
.mapToObj(String::valueOf)
.collect(joining(","))
+ "#" +
le.getValue().entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(joining("|"))
);
}