下面列出了java.util.stream.Stream#toArray ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void transform(final String normalisedName, String[] values, final ValueArrayConsumer consumer) throws
IOException {
Stream<String> stream = Arrays.stream(values);
// Remove empty values.
stream = stream.filter(value -> null != value && !value.isEmpty());
// Remove duplicates.
// Normalised to lowercase so that "GENERATOR" matches "Generator" (these inconsistent names can come from
// HTML documents).
if (values.length > 1 && deduplicateProperties.contains(fieldMap.get(normalisedName)
.toLowerCase(Locale.ENGLISH))) {
stream = stream.distinct();
}
values = stream.toArray(String[]::new);
if (values.length > 0) {
consumer.accept(normalisedName, values);
}
}
@Test
public void testSplitter() throws Exception {
ZipSplitter splitter = new ZipSplitter();
splitter.setEntryFilter(x -> x.getSize() > 50 ? true : false );
Stream<BytesHandle> contentStream = splitter.split(new ZipInputStream(new FileInputStream(zipFile)));
assertNotNull(contentStream);
BytesHandle[] bytesResult = contentStream.toArray(size -> new BytesHandle[size]);
assertNotNull(bytesResult);
assertEquals(bytesResult.length, 2);
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = null;
for (int i = 0; (zipEntry = zipInputStream.getNextEntry()) != null && i < bytesResult.length; i++) {
assertNotNull(bytesResult[i].get());
checkContent(zipInputStream, zipEntry, new String(bytesResult[i].get()));
}
}
@Deprecated
private SslContextFactory createSslContextFactoryFromTrustManagerProvider(@Nullable String endpoint) {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
if (endpoint != null && trustmanagerProvider != null) {
Stream<TrustManager> trustManagerStream = trustmanagerProvider.getTrustManagers(endpoint);
TrustManager[] trustManagers = trustManagerStream.toArray(TrustManager[]::new);
if (trustManagers.length > 0) {
logger.debug("using custom trustmanagers (certificate pinning) for httpClient for endpoint {}",
endpoint);
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, null);
sslContextFactory.setSslContext(sslContext);
} catch (NoSuchAlgorithmException | KeyManagementException ex) {
throw new HttpClientInitializationException(
"Cannot create an TLS context for the endpoint '" + endpoint + "'!", ex);
}
}
}
String excludeCipherSuites[] = { "^.*_(MD5)$" };
sslContextFactory.setExcludeCipherSuites(excludeCipherSuites);
return sslContextFactory;
}
@Test
public void testXMLSplitter() throws Exception {
XMLSplitter splitter = XMLSplitter.makeSplitter("http://www.marklogic.com/people/", "person");
FileInputStream fileInputStream = new FileInputStream(new File(xmlFile));
Stream<StringHandle> contentStream = splitter.split(fileInputStream);
assertNotNull(contentStream);
StringHandle[] result = contentStream.toArray(size -> new StringHandle[size]);
assertEquals(3, splitter.getCount());
assertNotNull(result);
for (int i = 0; i < result.length; i++) {
String element = result[i].get();
assertNotNull(element);
assertEquals(expected[i], element);
}
}
public static void main(String[] args) {
// String array
String[] arr = {"One", "Two", "Three", "Four", "Five"};
// array to Stream
Stream<String> stream1 = Arrays.stream(arr);
Stream<String> stream2 = Arrays.stream(arr, 0, 2);
Stream<String> stream3 = Arrays.asList(arr).stream();
Stream<String> stream4 = Arrays.asList(arr).subList(0, 2).stream();
Stream<String> stream5 = Stream.of(arr);
Stream<String> stream6 = Stream.of("One", "Two", "Three");
// Stream to array
String[] array1 = stream1.toArray(String[]::new);
// integers array
int[] integers = {2, 3, 4, 1};
Integer[] boxedInt = {2, 3, 4, 1};
IntStream intStream1 = Arrays.stream(integers);
IntStream intStream2 = IntStream.of(integers);
IntStream intStream3 = IntStream.range(0, integers.length);;
IntStream intStream4 = IntStream.rangeClosed(0, integers.length);
Stream<Integer> intStream5 = Stream.of(boxedInt);
int[] intArray1 = intStream1.toArray();
int[] intArray2 = intStream5.mapToInt(i -> i).toArray();
}
@Test(dataProvider = "collections")
public void testCollectionSizeRemove(String name, Collection<Integer> c) {
assertTrue(c.remove(1));
Stream<Integer> s = c.stream();
assertTrue(c.remove(2));
Object[] result = s.toArray();
assertEquals(result.length, c.size());
}
/**
* Has the given aggregation function process all elements of the stream, starting with the given initial element.
*/
@SuppressWarnings("unchecked")
public static <T,U> U foldLeft(U initial, Stream<T> stream, BiFunction<U,T,U> f) {
U u = initial;
for (Object t: stream.toArray()) {
u = f.apply(u, (T) t);
}
return u;
}
private void testEntrySetSizeRemove(String name, Set<Map.Entry<Integer, Integer>> c) {
Map.Entry<Integer, Integer> first = c.iterator().next();
assertTrue(c.remove(first));
Stream<Map.Entry<Integer, Integer>> s = c.stream();
Map.Entry<Integer, Integer> second = c.iterator().next();
assertTrue(c.remove(second));
Object[] result = s.toArray();
assertEquals(result.length, c.size());
}
@Test
public void noFallBackScanner_fallbackIsNotGenerated() throws IOException {
Stream<Class<?>> classes = Stream.concat(
Stream.of(NodeTestComponents.class.getDeclaredClasses()),
Stream.of(ExtraNodeTestComponents.class.getDeclaredClasses()));
ClassFinder classFinder = new DefaultClassFinder(
new URLClassLoader(getClassPath()),
classes.toArray(Class<?>[]::new));
updater = new TaskUpdateImports(classFinder,
new FrontendDependenciesScannerFactory().createScanner(false,
classFinder, true),
finder -> null, tmpRoot, generatedPath, frontendDirectory,
tokenFile, null, false) {
@Override
Logger log() {
return logger;
}
};
updater.execute();
assertTrue(importsFile.exists());
String mainContent = FileUtils.readFileToString(importsFile,
Charset.defaultCharset());
// fallback chunk load function is not generated
Assert.assertThat(mainContent,
CoreMatchers.not(CoreMatchers.containsString(
"window.Vaadin.Flow.loadFallback = function loadFallback(){")));
Assert.assertFalse(fallBackImportsFile.exists());
}
@Test(dataProvider = "collections")
public void testCollectionSizeRemove(String name, Collection<Integer> c) {
assertTrue(c.remove(1));
Stream<Integer> s = c.stream();
assertTrue(c.remove(2));
Object[] result = s.toArray();
assertEquals(result.length, c.size());
}
private void testEntrySetSizeRemove(String name, Set<Map.Entry<Integer, Integer>> c) {
Map.Entry<Integer, Integer> first = c.iterator().next();
assertTrue(c.remove(first));
Stream<Map.Entry<Integer, Integer>> s = c.stream();
Map.Entry<Integer, Integer> second = c.iterator().next();
assertTrue(c.remove(second));
Object[] result = s.toArray();
assertEquals(result.length, c.size());
}
public static String[] stringStreamToStringArrayUsingFunctionalInterface(Stream<String> stringStream) {
IntFunction<String[]> intFunction = new IntFunction<String[]>() {
@Override
public String[] apply(int value) {
return new String[value];
}
};
return stringStream.toArray(intFunction);
}
@Test(dataProvider = "collections")
public void testCollectionSizeRemove(String name, Collection<Integer> c) {
assertTrue(c.remove(1));
Stream<Integer> s = c.stream();
assertTrue(c.remove(2));
Object[] result = s.toArray();
assertEquals(result.length, c.size());
}
private void testEntrySetSizeRemove(String name, Set<Map.Entry<Integer, Integer>> c) {
Map.Entry<Integer, Integer> first = c.iterator().next();
assertTrue(c.remove(first));
Stream<Map.Entry<Integer, Integer>> s = c.stream();
Map.Entry<Integer, Integer> second = c.iterator().next();
assertTrue(c.remove(second));
Object[] result = s.toArray();
assertEquals(result.length, c.size());
}
@SuppressWarnings("unchecked")
public static <T> Stream<T> reverse(Stream<T> input) {
Object[] temp = input.toArray();
return (Stream<T>) IntStream.range(0, temp.length)
.mapToObj(i -> temp[temp.length - i - 1]);
}
public Employee[] arrayStream(){
Stream<Employee> serial = employeeDaoImpl.getEmployees().stream();
IntFunction<Employee[]> sizeEmpArr = (size) -> new Employee[size];
Employee[] arrEmps = serial.toArray(sizeEmpArr);
return arrEmps;
}
public static String[] stringStreamToStringArrayUsingLambda(Stream<String> stringStream) {
return stringStream.toArray(value -> new String[value]);
}
private static <T> CompletableFuture<T>[] toArray(final Stream<CompletableFuture<T>> stream) {
return stream.toArray(CompletableFuture[]::new);
}
public Container create() {
if (lifecycle.isClosed()) {
throw new IllegalStateException("ContainerManager already closed");
}
final String moduleLocation = classLoaderConfiguration.isSupportsResourceDependencies()
? nestedContainerMapping.getOrDefault(module, module)
: module;
final Path resolved = resolve(moduleLocation);
info("Creating module " + moduleLocation + " (from " + module
+ (Files.exists(resolved) ? ", location=" + resolved.toAbsolutePath().toString() : "") + ")");
final Stream<Artifact> classpath = Stream
.concat(getBuiltInClasspath(moduleLocation),
additionalClasspath == null ? Stream.empty() : additionalClasspath.stream());
final Container container = new Container(id, moduleLocation, classpath.toArray(Artifact[]::new),
classLoaderConfiguration, ContainerManager.this::resolve,
ofNullable(containerInitializer)
.orElse(NOOP_CUSTOMIZER)
.andThen(ofNullable(customizer).orElse(NOOP_CUSTOMIZER)),
jvmMarkers, hasNestedRepository) {
@Override
public void close() {
setState(State.UNDEPLOYING);
try {
listeners.forEach(l -> safeInvoke(() -> l.onClose(this)));
} finally {
try {
super.close();
} finally {
containers.remove(id);
setState(State.UNDEPLOYED);
}
}
info("Closed container " + id);
}
};
container.setState(Container.State.CREATED);
container.set(ContainerBuilder.class, this);
container.set(Actions.class, new Actions(container));
final Collection<RuntimeException> re = new ArrayList<>();
final ConfigurableClassLoader loader = container.getLoader();
final Thread thread = Thread.currentThread();
final ClassLoader oldLoader = thread.getContextClassLoader();
thread.setContextClassLoader(loader);
try {
final Collection<ContainerListener> calledListeners = listeners
.stream()
.filter(l -> !ofNullable(safeInvoke(() -> l.onCreate(container))).map(re::add).orElse(false))
.collect(toList());
if (calledListeners.size() == listeners.size()) {
if (containers.putIfAbsent(id, container) != null) {
container.setState(Container.State.ON_ERROR);
calledListeners.forEach(l -> safeInvoke(() -> l.onClose(container)));
throw new IllegalArgumentException("Container '" + id + "' already exists");
}
} else {
info("Failed creating container " + id);
calledListeners.forEach(l -> safeInvoke(() -> l.onClose(container)));
final IllegalArgumentException exception = new IllegalArgumentException(id + " can't be deployed");
re.forEach(exception::addSuppressed);
throw exception;
}
} finally {
thread.setContextClassLoader(oldLoader);
}
container.setState(Container.State.DEPLOYED);
info("Created container " + id);
return container;
}
/**
* Returns an array containing the elements of the stream.
* <pre class="groovyTestCase">
* import static groovy.test.GroovyAssert.shouldFail
*
* assert Arrays.equals([].stream().toArray(Object), new Object[0])
* assert Arrays.equals([].stream().toArray(String), new String[0])
* assert Arrays.equals([].stream().toArray(String[]), new String[0][])
* assert Arrays.equals(['x'].stream().toArray(Object), ['x'].toArray())
* assert Arrays.equals(['x'].stream().toArray(String), ['x'] as String[])
* assert Arrays.deepEquals([['x'] as String[]].stream().toArray(String[]), [['x'] as String[]] as String[][])
* assert Arrays.equals(['x'].stream().toArray(CharSequence), ['x'] as CharSequence[])
*
* shouldFail(ArrayStoreException) {
* ['x'].stream().toArray(Thread)
* }
*
* shouldFail(IllegalArgumentException) {
* ['x'].stream().toArray((Class) null)
* }
*
* // Stream#toArray(IntFunction) should still be used for closure literal:
* assert Arrays.equals(['x'].stream().toArray { n -> new String[n] }, ['x'] as String[])
*
* // Stream#toArray(IntFunction) should still be used for method reference:
* assert Arrays.equals(['x'].stream().toArray(String[]::new), ['x'] as String[])
* </pre>
*
* @param self the stream
* @param type the array element type
*
* @since 3.0.4
*/
public static <T> T[] toArray(final Stream<? extends T> self, final Class<T> type) {
if (type == null) throw new IllegalArgumentException("type cannot be null");
return self.toArray(length -> (T[]) Array.newInstance(type, length));
}