Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on the Stream Object in Java 8

Comemnts

  1. 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.

  2. 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);
}
8.0
7.0
5.0
Out[14]:
null

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);
}
3
5
5
3
5
4
3
4
3
Out[7]:
null

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();
incompatible types: java.lang.Object[] cannot be converted to int[]
 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);
}
3
5
5
3
5
4
3
4
3
Out[12]:
null

Comments