|
| 1 | +package lambdasinaction.chap4; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.util.function.IntSupplier; |
| 5 | +import java.util.stream.*; |
| 6 | +import static java.util.stream.Collectors.toList; |
| 7 | +import java.nio.charset.Charset; |
| 8 | +import java.nio.file.*; |
| 9 | + |
| 10 | +public class BuildingStreams { |
| 11 | + |
| 12 | + public static void main(String...args) throws Exception{ |
| 13 | + |
| 14 | + // Stream.of |
| 15 | + Stream<String> stream = Stream.of("Java 8", "Lambdas", "In", "Action"); |
| 16 | + stream.map(String::toUpperCase).forEach(System.out::println); |
| 17 | + |
| 18 | + // Stream.empty |
| 19 | + Stream<String> emptyStream = Stream.empty(); |
| 20 | + |
| 21 | + // Arrays.stream |
| 22 | + int[] numbers = {2, 3, 5, 7, 11, 13}; |
| 23 | + System.out.println(Arrays.stream(numbers).sum()); |
| 24 | + |
| 25 | + // Stream.iterate |
| 26 | + Stream.iterate(0, n -> n + 2) |
| 27 | + .limit(10) |
| 28 | + .forEach(System.out::println); |
| 29 | + |
| 30 | + // fibonnaci with iterate |
| 31 | + Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1],t[0] + t[1]}) |
| 32 | + .limit(10) |
| 33 | + .forEach(t -> System.out.println("(" + t[0] + ", " + t[1] + ")")); |
| 34 | + |
| 35 | + Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1],t[0] + t[1]}) |
| 36 | + .limit(10) |
| 37 | + . map(t -> t[0]) |
| 38 | + .forEach(System.out::println); |
| 39 | + |
| 40 | + // random stream of doubles with Stream.generate |
| 41 | + Stream.generate(Math::random) |
| 42 | + .limit(10) |
| 43 | + .forEach(System.out::println); |
| 44 | + |
| 45 | + // stream of 1s with Stream.generate |
| 46 | + IntStream.generate(() -> 1) |
| 47 | + .limit(5) |
| 48 | + .forEach(System.out::println); |
| 49 | + |
| 50 | + IntStream.generate(new IntSupplier(){ |
| 51 | + public int getAsInt(){ |
| 52 | + return 2; |
| 53 | + } |
| 54 | + }).limit(5) |
| 55 | + .forEach(System.out::println); |
| 56 | + |
| 57 | + |
| 58 | + IntSupplier fib = new IntSupplier(){ |
| 59 | + private int previous = 0; |
| 60 | + private int current = 1; |
| 61 | + public int getAsInt(){ |
| 62 | + int nextValue = this.previous + this.current; |
| 63 | + this.previous = this.current; |
| 64 | + this.current = nextValue; |
| 65 | + return this.previous; |
| 66 | + } |
| 67 | + }; |
| 68 | + IntStream.generate(fib).limit(10).forEach(System.out::println); |
| 69 | + |
| 70 | + long uniqueWords = Files.lines(Paths.get("lambdasinaction/chap4/data.txt"), Charset.defaultCharset()) |
| 71 | + .flatMap(line -> Arrays.stream(line.split(" "))) |
| 72 | + .distinct() |
| 73 | + .count(); |
| 74 | + |
| 75 | + System.out.println("There are " + uniqueWords + " unique words in data.txt"); |
| 76 | + |
| 77 | + |
| 78 | + } |
| 79 | +} |
0 commit comments