Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

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

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
null

Sum Integer Values

integers.values().stream().mapToInt(i -> i.intValue()).sum();
integers.values().stream().mapToInt(Integer::intValue).sum();

Taking Elements By Indexes

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.

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
null

Calling Stream.map followed Stream.toArray cannot convert a Stream to a primitive array.

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

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
null