4
String[] arr={"121","4545","45456464"};
Arrays.stream(arr).filter(s->s.length()>4).toArray(String[]::new);

Can someone tell me exactly what's happening with toArray(String[]::new) in above code snippet.

Stefan Zobel
  • 2,799
  • 7
  • 23
  • 33
vny uppara
  • 119
  • 6
  • 3
    So, is this question about `filter` or about `toArray`? – tobias_k Jan 30 '17 at 09:32
  • 1
    Possible duplicate of [How to Convert a Java 8 Stream to an Array?](http://stackoverflow.com/questions/23079003/how-to-convert-a-java-8-stream-to-an-array) – Didier L Jan 30 '17 at 15:41

3 Answers3

5

String[]::new is actually the same as size -> new String[size]. A new String[] is created with the same size as the number of elements after applying the filter to the Stream. See also the javadoc of Stream.toArray

Roland
  • 18,065
  • 1
  • 39
  • 71
3

The toArray is creating a String[] containing the result of the filter in your case all strings whose length is greater than 4. The filter returns a Stream and so you are converting it into an array.

To print the filtered result rather than storing it into an array

Arrays.stream(arr).filter(s -> s.length() > 4).forEach(System.out::println);
Aimee Borda
  • 822
  • 2
  • 11
  • 22
  • How to print that string? – vny uppara Jan 30 '17 at 08:48
  • 1
    Do you mean rather than storing it back to `String[]` or how to print an array in general. I updated the answer to show how you can print a stream – Aimee Borda Jan 30 '17 at 08:51
  • If the value is stored in String as mentioned in question and what is the reference for that String and how to access it? – vny uppara Jan 30 '17 at 08:54
  • 1
    `String[]::new` is called constructor reference in java which is the same as `new String[size]` as explained in the other answer. `toArray` returns that array. – Aimee Borda Jan 30 '17 at 09:01
  • 1
    @vnyuppara if you want one String use `.collect(Collectors.joining(","))` using `toArray` returns an array. – Peter Lawrey Jan 30 '17 at 09:34
1

String[]::new is a reference to new operator of String[] type. It is Java-8 syntax. toArray method of Streams take an IntFunction<A[]> as the generator for the array in which elements of the stream will be collected. It is the same as writing:

Arrays.stream(arr).filter(s->s.length()>4).toArray(size-> { return new Integer[size]; });
Jean-Baptiste Yunès
  • 30,872
  • 2
  • 40
  • 66