How to Convert a Java 8 Stream to an Array ?

How to Convert a Java 8 Stream to an Array ?

Asked on December 6, 2018 in Java.
Add Comment


  • 4 Answer(s)

    You can create a custom collector that convert a stream to array.

    public static <T> Collector<T, ?, T[]> toArray( IntFunction<T[]> converter )
    {
        return Collectors.collectingAndThen( 
                      Collectors.toList(), 
                      list ->list.toArray( converter.apply( list.size() ) ) );
    }

    and a quick use

    List<String> input = Arrays.asList( ..... );
    
    String[] result = input.stream().
             .collect( CustomCollectors.**toArray**( String[]::new ) );
    Answered on January 18, 2019.
    Add Comment

    convert a Stream to an array, there is an overloaded version of toArray() method for Stream objects. The toArray(IntFunction<A[]> generator) method returns an array containing the elements of this stream, using the provided generator function to allocate the returned array.

    String[] stringArr = { "a", "b", "c", "d" };
    Stream<String> stream = Stream.of(stringArr);
    String[] arr = stream.toArray(size -> new String[size]);
    System.out.println(Arrays.toString(arr));
    Answered on January 18, 2019.
    Add Comment

    You can create a custom collector that convert a stream to array.

    public static <T> Collector<T, ?, T[]> toArray( IntFunction<T[]> converter )
    {
        return Collectors.collectingAndThen( 
                      Collectors.toList(), 
                      list ->list.toArray( converter.apply( list.size() ) ) );
    }

    and a quick use

    List<String> input = Arrays.asList( ..... );
    
    String[] result = input.stream().
             .collect( CustomCollectors.**toArray**( String[]::new ) );
    Answered on January 18, 2019.
    Add Comment

    You can create a custom collector that convert a stream to array.

    public static <T> Collector<T, ?, T[]> toArray( IntFunction<T[]> converter )
    {
        return Collectors.collectingAndThen( 
                      Collectors.toList(), 
                      list ->list.toArray( converter.apply( list.size() ) ) );
    }

    and a quick use

    List<String> input = Arrays.asList( ..... );
    
    String[] result = input.stream().
             .collect( CustomCollectors.**toArray**( String[]::new ) );
    Answered on January 18, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.