|
1 | 1 | package io.javabrains.reactiveworkshop;
|
2 | 2 |
|
| 3 | +import java.util.stream.Stream; |
| 4 | + |
3 | 5 | public class Exercise1 {
|
4 | 6 |
|
5 | 7 | public static void main(String[] args) {
|
6 | 8 |
|
7 | 9 | // Use StreamSources.intNumbersStream() and StreamSources.userStream()
|
8 | 10 |
|
9 | 11 | // Print all numbers in the intNumbersStream stream
|
10 |
| - // TODO: Write code here |
| 12 | +// StreamSources.intNumbersStream().forEach(System.out::println); |
| 13 | + printStream(StreamSources.intNumbersStream()); |
11 | 14 |
|
12 | 15 | // Print numbers from intNumbersStream that are less than 5
|
13 |
| - // TODO: Write code here |
| 16 | +// StreamSources.intNumbersStream().filter(n -> n < 5).forEach(System.out::println); |
| 17 | + printStream(StreamSources.intNumbersStream().filter(n -> n < 5)); |
14 | 18 |
|
15 | 19 | // Print the second and third numbers in intNumbersStream that's greater than 5
|
16 |
| - // TODO: Write code here |
| 20 | + printStream(StreamSources.intNumbersStream().filter(n -> n > 5) |
| 21 | + .skip(1) |
| 22 | + .limit(2)); |
17 | 23 |
|
18 | 24 | // Print the first number in intNumbersStream that's greater than 5.
|
19 | 25 | // If nothing is found, print -1
|
20 |
| - // TODO: Write code here |
| 26 | + printStream(StreamSources.intNumbersStream() |
| 27 | + .filter(n -> n > 5) |
| 28 | + .findFirst() |
| 29 | + .orElse(-1) |
| 30 | + ); |
21 | 31 |
|
22 | 32 | // Print first names of all users in userStream
|
23 |
| - // TODO: Write code here |
| 33 | + printStream(StreamSources.userStream().map(user -> user.getFirstName())); |
24 | 34 |
|
25 | 35 | // Print first names in userStream for users that have IDs from number stream
|
26 |
| - // TODO: Write code here |
| 36 | + printStream(StreamSources.intNumbersStream() |
| 37 | + .flatMap(id -> StreamSources.userStream().filter(user -> user.getId() == id)) |
| 38 | + .map(user -> String.format("%s %s", user.getFirstName(), user.getLastName()))); |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + private static void printStream(Stream s) { |
| 43 | + System.out.println("-*-*-*-*-*-*-*-*-*-"); |
| 44 | + s.forEach(System.out::println); |
| 45 | + } |
27 | 46 |
|
| 47 | + private static void printStream(int s) { |
| 48 | + System.out.println("-*-*-*-*-*-*-*-*-*-"); |
| 49 | + System.out.println(s); |
28 | 50 | }
|
29 | 51 |
|
30 | 52 | }
|
0 commit comments