Java Code Examples for java.util.stream.Stream#toArray()

The following examples show how to use java.util.stream.Stream#toArray() . 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: MetadataTransformer.java    From extract with MIT License 6 votes vote down vote up
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);
	}
}
 
Example 2
Source File: XMLSplitterTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 3
Source File: WebClientFactoryImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@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;
}
 
Example 4
Source File: ZipSplitterTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
@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()));
    }
}
 
Example 5
Source File: CollectionAndMapModifyStreamTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
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());
}
 
Example 6
Source File: NodeUpdateImportsTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@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());

}
 
Example 7
Source File: CollectionAndMapModifyStreamTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example 8
Source File: CollectionAndMapModifyStreamTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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());
}
 
Example 9
Source File: StreamArrayConversion.java    From tutorials with MIT License 5 votes vote down vote up
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);
}
 
Example 10
Source File: JavaStreams.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 11
Source File: CollectionAndMapModifyStreamTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example 12
Source File: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
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();
    }
 
Example 13
Source File: CollectionAndMapModifyStreamTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example 14
Source File: CollectionAndMapModifyStreamTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
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());
}
 
Example 15
Source File: Util.java    From native-obfuscator with GNU General Public License v3.0 4 votes vote down vote up
@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]);
}
 
Example 16
Source File: EmployeeStreamService.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
public Employee[] arrayStream(){
	Stream<Employee> serial = employeeDaoImpl.getEmployees().stream();
	IntFunction<Employee[]> sizeEmpArr = (size) -> new Employee[size];
	Employee[] arrEmps = serial.toArray(sizeEmpArr);
	return arrEmps;
}
 
Example 17
Source File: StreamArrayConversion.java    From tutorials with MIT License 4 votes vote down vote up
public static String[] stringStreamToStringArrayUsingLambda(Stream<String> stringStream) {
    return stringStream.toArray(value -> new String[value]);
}
 
Example 18
Source File: Github.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private static <T> CompletableFuture<T>[] toArray(final Stream<CompletableFuture<T>> stream) {
    return stream.toArray(CompletableFuture[]::new);
}
 
Example 19
Source File: ContainerManager.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 20
Source File: PluginDefaultGroovyMethods.java    From groovy with Apache License 2.0 2 votes vote down vote up
/**
 * 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));
}