Collect Results of a Stream into an Array

suggest change

Analog to get a collection for a Stream by collect() an array can be obtained by the Stream.toArray() method:

List<String> fruits = Arrays.asList("apple", "banana", "pear", "kiwi", "orange");

String[] filteredFruits = fruits.stream()
    .filter(s -> s.contains("a"))
    .toArray(String[]::new);     

// prints: [apple, banana, pear, orange]
System.out.println(Arrays.toString(filteredFruits));

String[]::new is a special kind of method reference: a constructor reference.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents