vny uppara
vny uppara

Reputation: 119

Using filter in streams

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.

Upvotes: 4

Views: 169

Answers (3)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36441

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]; });

Upvotes: 1

Roland
Roland

Reputation: 23352

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

Upvotes: 5

Aimee Borda
Aimee Borda

Reputation: 842

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);

Upvotes: 3

Related Questions