s.length()>4).toArray(String[]::new); Can som...">

Using a filter in streams

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

Can someone tell me what happens with toArray(String[]::new)in the code snippet.

+4
source share
3 answers

String[]::newactually matches size -> new String[size]. A new one String[]is created with the same size as the number of elements after applying filterto Stream. See also javadocStream.toArray

+5
source

toArraycreates String[], containing the result filter, in your case, all lines whose length is greater than 4. filterreturns a Stream, and therefore you convert it to an array.

To print the filtered result, rather than save it to an array

Arrays.stream(arr).filter(s -> s.length() > 4).forEach(System.out::println);
+3
source

String[]::new String[]. Java-8. toArray Streams IntFunction<A[]> , . , :

Arrays.stream(arr).filter(s->s.length()>4).toArray(size-> { return new Integer[size]; });
+1
source

Source: https://habr.com/ru/post/1668231/


All Articles