Comemnts¶
Stream (introduced in Java 8) brings functional programming into Java so that coding in Java is easier and faster but at the cost of performance. Code written in Stream is slower than non-stream and lambda based Java code, generally speaking.
The method
Stream.map
is not friendly on conversion to Arrays.Stream.mapToInt
,Stream.mapToLong
, etc. are better alternatives if you need to to convert a Stream object to an Array.
Stream.filter¶
In [14]:
import java.util.Arrays;
double[] arr = {8, 7, -6, 5, -4};
arr = Arrays.stream(arr).filter(x -> x > 0).toArray();
for (double elem : arr) {
System.out.println(elem);
}
Out[14]:
Sum Integer Values¶
In [ ]:
integers.values().stream().mapToInt(i -> i.intValue()).sum();
integers.values().stream().mapToInt(Integer::intValue).sum();
Taking Elements By Indexes¶
In [ ]:
Card[] threeCards = (Card[]) Arrays.stream(index).mapToObj(i -> leftCards[i]).toArray();
Convert a Stream to a Primitive Array¶
You can call the Stream.mapTo*
method (NOT Stream.map
) followed by Stream.toArray
to convert a Stream to a primitive Array.
In [7]:
import java.util.Arrays;
String[] words = new String[] {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};
int[] lens = Arrays.stream(words).mapToInt(word -> word.length()).toArray();
for(int len : lens){
System.out.println(len);
}
Out[7]:
Calling Stream.map
followed Stream.toArray
cannot convert a Stream to a primitive array.
In [9]:
import java.util.Arrays;
String[] words = new String[] {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};
int[] lens = Arrays.stream(words).map(word -> word.length()).toArray();
Convert A Stream to an Object Array¶
In [12]:
import java.util.Arrays;
String[] words = new String[] {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};
Integer[] lens = Arrays.stream(words).map(word -> word.length()).toArray(Integer[]::new);
for(int len : lens){
System.out.println(len);
}
Out[12]: