An important aspect of steam is that they are lazy which means they are only evaluated when ablolutely necessary.
There are three types of operations: creating streams, modifying elements of a stream (intermediate operation), and consuming stream elements (terminal operations).
// streams/CollectionToStream.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
import java.util.stream.*;
public class CollectionToStream {
public static void main(String[] args) {
List<Bubble> bubbles = Arrays.asList(new Bubble(1), new Bubble(2), new Bubble(3));
System.out.println("bubbles.stream():" + bubbles.stream());
System.out.println(
"bubbles.stream().mapToInt(b -> b.i):" + bubbles.stream().mapToInt(b -> b.i));
System.out.println(bubbles.stream().mapToInt(b -> b.i).sum()); // stream(), interface Collection default method since 1.8
Set<String> w = new HashSet<>(Arrays.asList("It's a wonderful day for pie!".split(" ")));
w.stream().map(x -> x + " ").forEach(System.out::print); // Lambda Expression + method reference since 1.8
System.out.println();
Map<String, Double> m = new HashMap<>();
m.put("pi", 3.14159);
m.put("e", 2.718);
m.put("phi", 1.618);
System.out.println("m:" + m);
System.out.println("m.entrySet():" + m.entrySet());
m.entrySet().stream().map(e -> e.getKey() + ": " + e.getValue()).forEach(System.out::println);
}
}
/*My Output:
bubbles.stream():java.util.stream.ReferencePipeline$Head@7852e922
bubbles.stream().mapToInt(b -> b.i):java.util.stream.ReferencePipeline$4@53d8d10a
6
a pie! It's for wonderful day
m:{phi=1.618, e=2.718, pi=3.14159}
m.entrySet():[phi=1.618, e=2.718, pi=3.14159]
phi: 1.618
e: 2.718
pi: 3.14159
*/
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/CollectionToStream.java
3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Bubble.java
4. https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#stream--
6. https://howtodoinjava.com/java-8-tutorial/
7. https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#entrySet--