Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 721
vny uppara Avatar asked Jan 05 '23 15:01

vny uppara


2 Answers

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

like image 89
Roland Avatar answered Jan 07 '23 04:01

Roland


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);
like image 43
Aimee Borda Avatar answered Jan 07 '23 04:01

Aimee Borda