Example usage for java.util.stream Stream toArray

List of usage examples for java.util.stream Stream toArray

Introduction

In this page you can find the example usage for java.util.stream Stream toArray.

Prototype

<A> A[] toArray(IntFunction<A[]> generator);

Source Link

Document

Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.

Usage

From source file:Main.java

public static void main(String[] args) {
    // collect as typed array
    Stream<String> words = Stream.of("All", "men", "are", "created", "equal");
    final String[] wordsArray = words.toArray(String[]::new);
    Arrays.asList(wordsArray).forEach(n -> System.out.println(n));
}

From source file:Main.java

public static void main(String[] args) {

    int[] intArray = { 1, 2, 3, 4 };
    Stream<int[]> singleElementStream = Stream.of(intArray);

    // OUTPUTS//from   ww w  .  j av a  2s. c o m

    System.out.println(Arrays.toString(singleElementStream.toArray(Integer[]::new)));
    singleElementStream.toArray(); // watch it, it is Object[]
}

From source file:com.joyent.manta.client.MantaClientFindIT.java

/**
 * This test determines that we are filtering results as per our expection
 * when using a filter predicate with find().
 *//*  w  w w .  j  a  v  a  2s  .c  o  m*/
public void canFindRecursivelyWithFilter() throws IOException {
    List<String> level1Dirs = Arrays.asList(testPathPrefix + "aaa_bbb_ccc", testPathPrefix + "aaa_111_ccc",
            testPathPrefix + UUID.randomUUID());

    List<String> level1Files = Arrays.asList(testPathPrefix + UUID.randomUUID(),
            testPathPrefix + "aaa_222_ccc");

    for (String dir : level1Dirs) {
        mantaClient.putDirectory(dir);
    }

    for (String file : level1Files) {
        mantaClient.put(file, TEST_DATA, StandardCharsets.UTF_8);
    }

    List<String> level2Files = level1Dirs.stream().flatMap(dir -> Stream.of(dir + SEPARATOR + "aaa_333_ccc",
            dir + SEPARATOR + "aaa_444_ccc", dir + SEPARATOR + UUID.randomUUID())).collect(Collectors.toList());

    for (String file : level2Files) {
        mantaClient.put(file, TEST_DATA, StandardCharsets.UTF_8);
    }

    final String[] results;

    Predicate<? super MantaObject> filter = (Predicate<MantaObject>) obj -> FilenameUtils.getName(obj.getPath())
            .startsWith("aaa_");

    try (Stream<MantaObject> stream = mantaClient.find(testPathPrefix, filter)) {
        Stream<String> paths = stream.map(MantaObject::getPath);
        Stream<String> sorted = paths.sorted();
        results = sorted.toArray(String[]::new);
    }

    String[] expected = new String[] { testPathPrefix + "aaa_111_ccc",
            testPathPrefix + "aaa_111_ccc" + SEPARATOR + "aaa_333_ccc",
            testPathPrefix + "aaa_111_ccc" + SEPARATOR + "aaa_444_ccc", testPathPrefix + "aaa_222_ccc",
            testPathPrefix + "aaa_bbb_ccc", testPathPrefix + "aaa_bbb_ccc" + SEPARATOR + "aaa_333_ccc",
            testPathPrefix + "aaa_bbb_ccc" + SEPARATOR + "aaa_444_ccc", };

    try {
        Assert.assertEqualsNoOrder(results, expected);
    } catch (AssertionError e) {
        System.err.println("ACTUAL:   " + StringUtils.join(results, ", "));
        System.err.println("EXPECTED: " + StringUtils.join(expected, ", "));
        throw e;
    }
}

From source file:org.ow2.proactive.workflow_catalog.rest.util.ArchiveManagerHelper.java

/**
 * Compress a list of WorkflowRevision into a ZIP archive
 * @param workflowsList the list of workflows to compress
 * @return a byte array corresponding to the archive containing the workflows
 *//*from www .  j a v  a  2  s  .  c  o  m*/
public byte[] compressZIP(List<WorkflowRevision> workflowsList) {

    if (workflowsList == null || workflowsList.size() == 0) {
        return null;
    }

    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

        Stream<ZipEntrySource> streamSources = workflowsList.stream()
                .map(workflowRevision -> new ByteSource(getName(workflowRevision),
                        workflowRevision.getXmlPayload()));
        ZipEntrySource[] sources = streamSources.toArray(size -> new ZipEntrySource[size]);
        ZipUtil.pack(sources, byteArrayOutputStream);

        return byteArrayOutputStream.toByteArray();
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

}

From source file:com.ikanow.aleph2.core.shared.services.ReadOnlyMultiCrudService.java

/**
 * @return/*from   w w w. j  a v a  2  s  . c o m*/
 * @see com.ikanow.aleph2.data_model.interfaces.shared_services.ICrudService#countObjects()
 */
public CompletableFuture<Long> countObjects() {
    final Stream<CompletableFuture<Long>> intermed_res1 = _services.stream().map(s -> s.countObjects());

    @SuppressWarnings("unchecked")
    CompletableFuture<Long>[] intermed_res2 = (CompletableFuture<Long>[]) intermed_res1
            .toArray(CompletableFuture[]::new);

    return CompletableFuture.allOf(intermed_res2).thenApply(__ -> {
        return Arrays.stream(intermed_res2).map(res -> res.join()).reduce((a, b) -> a + b).orElse(0L);
    });
}

From source file:com.ikanow.aleph2.core.shared.services.ReadOnlyMultiCrudService.java

/**
 * @param spec/* w  ww .jav a  2s  .  com*/
 * @return
 * @see com.ikanow.aleph2.data_model.interfaces.shared_services.ICrudService#countObjectsBySpec(com.ikanow.aleph2.data_model.utils.CrudUtils.QueryComponent)
 */
public CompletableFuture<Long> countObjectsBySpec(QueryComponent<T> spec) {
    final Stream<CompletableFuture<Long>> intermed_res1 = _services.stream()
            .map(s -> s.countObjectsBySpec(spec));

    @SuppressWarnings("unchecked")
    CompletableFuture<Long>[] intermed_res2 = (CompletableFuture<Long>[]) intermed_res1
            .toArray(CompletableFuture[]::new);

    return CompletableFuture.allOf(intermed_res2).thenApply(__ -> {
        return Arrays.stream(intermed_res2).map(res -> res.join()).reduce((a, b) -> a + b).orElse(0L);
    });
}

From source file:com.ikanow.aleph2.core.shared.services.ReadOnlyMultiCrudService.java

/**
 * @param id/* w ww .  j a v a  2  s.  c om*/
 * @param field_list
 * @param include
 * @return
 * @see com.ikanow.aleph2.data_model.interfaces.shared_services.ICrudService#getObjectById(java.lang.Object, java.util.List, boolean)
 */
public CompletableFuture<Optional<T>> getObjectById(Object id, List<String> field_list, boolean include) {

    final Stream<CompletableFuture<Optional<T>>> intermed_res1 = _services.stream()
            .map(s -> s.getObjectById(id, field_list, include));

    @SuppressWarnings("unchecked")
    CompletableFuture<Optional<T>>[] intermed_res2 = (CompletableFuture<Optional<T>>[]) intermed_res1
            .toArray(CompletableFuture[]::new);

    return CompletableFuture.allOf(intermed_res2).thenApply(__ -> {
        return Arrays.stream(intermed_res2).map(res -> res.join()).filter(maybe -> maybe.isPresent())
                .map(maybe -> maybe.get()).findFirst();
    });
}

From source file:com.ikanow.aleph2.core.shared.services.ReadOnlyMultiCrudService.java

/**
 * @param unique_spec//from w  w  w  .  java 2 s  .com
 * @param field_list
 * @param include
 * @return
 * @see com.ikanow.aleph2.data_model.interfaces.shared_services.ICrudService#getObjectBySpec(com.ikanow.aleph2.data_model.utils.CrudUtils.QueryComponent, java.util.List, boolean)
 */
public CompletableFuture<Optional<T>> getObjectBySpec(QueryComponent<T> unique_spec, List<String> field_list,
        boolean include) {
    final Stream<CompletableFuture<Optional<T>>> intermed_res1 = _services.stream()
            .map(s -> s.getObjectBySpec(unique_spec, field_list, include));

    @SuppressWarnings("unchecked")
    CompletableFuture<Optional<T>>[] intermed_res2 = (CompletableFuture<Optional<T>>[]) intermed_res1
            .toArray(CompletableFuture[]::new);

    return CompletableFuture.allOf(intermed_res2).thenApply(__ -> {
        return Arrays.stream(intermed_res2).map(res -> res.join()).filter(maybe -> maybe.isPresent())
                .map(maybe -> maybe.get()).findFirst();
    });
}

From source file:com.ikanow.aleph2.core.shared.services.ReadOnlyMultiCrudService.java

/**
 * @param spec/*from  w ww  .ja va2  s .c  o m*/
 * @param field_list
 * @param include
 * @return
 * @see com.ikanow.aleph2.data_model.interfaces.shared_services.ICrudService#getObjectsBySpec(com.ikanow.aleph2.data_model.utils.CrudUtils.QueryComponent, java.util.List, boolean)
 */
public CompletableFuture<ICrudService.Cursor<T>> getObjectsBySpec(QueryComponent<T> spec,
        List<String> field_list, boolean include) {

    final Stream<CompletableFuture<ICrudService.Cursor<T>>> intermed_res1 = _services.stream()
            .map(s -> s.getObjectsBySpec(spec, field_list, include));

    @SuppressWarnings("unchecked")
    CompletableFuture<ICrudService.Cursor<T>>[] intermed_res2 = (CompletableFuture<ICrudService.Cursor<T>>[]) intermed_res1
            .toArray(CompletableFuture[]::new);

    return CompletableFuture.allOf(intermed_res2).thenApply(__ -> {
        return new MultiCursor<T>(
                Arrays.stream(intermed_res2).map(res -> res.join()).collect(Collectors.toList()));
    });
}

From source file:alfio.manager.EventManager.java

MapSqlParameterSource[] prepareTicketsBulkInsertParameters(ZonedDateTime creation, Event event,
        int requestedTickets, TicketStatus ticketStatus) {

    //FIXME: the date should be inserted as ZonedDateTime !
    Date creationDate = Date.from(creation.toInstant());

    List<TicketCategory> categories = ticketCategoryRepository.findByEventId(event.getId());
    Stream<MapSqlParameterSource> boundedTickets = categories.stream().filter(IS_CATEGORY_BOUNDED)
            .flatMap(tc -> generateTicketsForCategory(tc, event, creationDate, 0));
    int generatedTickets = categories.stream().filter(IS_CATEGORY_BOUNDED)
            .mapToInt(TicketCategory::getMaxTickets).sum();
    if (generatedTickets >= requestedTickets) {
        return boundedTickets.toArray(MapSqlParameterSource[]::new);
    }/*  w w  w .  j a  v a 2s. co m*/

    return Stream.concat(boundedTickets,
            generateEmptyTickets(event, creationDate, requestedTickets - generatedTickets, ticketStatus))
            .toArray(MapSqlParameterSource[]::new);
}