Compare commits

...

2 Commits

Author SHA1 Message Date
Tristan B. Velloza Kildaire b909ddb6a4 MoreStreams
- Added example of `flatMap()`
2023-09-26 14:04:42 +02:00
Tristan B. Velloza Kildaire c628813d30 MoreStreams
- Added examples of using `anyMatch(Predicate<T>)`, `allMatch(Predicate<T>)` and `T findFirst()`
2023-09-26 13:47:47 +02:00
1 changed files with 69 additions and 2 deletions

View File

@ -17,10 +17,77 @@ public class App
// practiceDirtyLinkage();
// Practice parrallel streams (distinct)
parrallelStreams();
// parrallelStreams();
// Reduction examples (with Optionals)
reductionExamples();
// reductionExamples();
// Stream operations (findFirst, anyMatch, allMatch)
matchingExamples();
// Flat mapping
flatMapping();
}
/**
* Takes one stream and let's you map T -> Stream<T>
* and then have that flattened into one stream
* exhausting each
*
* Best example would be splitting words across
* multiple lines. First we start by splitting
* it linefeed-wise and then word wise on each
* provided linefeed, producing a new stream.
*
* All these streams are exhausted, then moved
* on to the next until that too is exhausted
*/
private static void flatMapping()
{
String originalText = """
This is my sentence
and
it is
sexy
""";
Stream<String> lines = Stream.of(originalText.split("\n"));
lines.flatMap((line) -> Stream.of(line.split(" ")))
.forEach((word) -> System.out.println(word));
// This is my sentence and it is sexy
}
/**
* Playing around with {@link Stream#findFirst()},
* {@link Stream#anyMatch(java.util.function.Predicate)}
* and {@link Stream#allMatch(java.util.function.Predicate)}
*/
private static void matchingExamples()
{
Stream<Integer> stream = Stream.of(1, 2, 2, 3, 4, 5, 6, 7, 2, 9, 5);
/**
* Terminal operation returning the first item
* in the stream
*/
Optional<Integer> optional = stream.parallel().findFirst();
System.out.println(optional.get()); // Finds first element, so 1
/**
* Terminal operation which return whether
* anything in the stream matched it
*/
stream = Stream.of(1, 2, 2, 3, 4, 5, 6, 7, 2, 9, 5).parallel();
System.out.println(stream.anyMatch((i) -> i > 5)); // true
/**
* Terminal operation returning
* whether or not ALL elements
* of the stream matched the
* given predicate
*/
stream = Stream.of(1, 2, 2, 3, 4, 5, 6, 7, 2, 9, 5).parallel();
System.out.println(stream.allMatch((i) -> i>5)); // false
}
/**