Creation and basics
IntStream.rangeClosed. Then list all primes up to 100 using noneMatch, and convert between IntStream, Stream<Integer> and int[] using boxed, mapToInt and toArray.Stream.of, a string's chars(), Stream.generate with limit, and the three-argument Stream.iterate with a predicate. Print each one, and note in comments which are infinite.page(List<String> data, int pageNo, int pageSize) method using skip and limit. Before paging, clean the data with filter, map(String::trim), distinct and sorted. Handle out-of-range pages.takeWhile to get readings until the first one above 40, and dropWhile to get everything after it. Explain in a comment why these differ from filter on sorted data.Collectors
groupingBy. Count each bracket and print the result as a tidy tree.Map<String, Double> with toMap. First show the IllegalStateException on duplicate keys, then fix it with a merge function that keeps the higher price. Use a LinkedHashMap supplier to keep insertion order.partitioningBy to split students into pass and fail, with a downstream averagingDouble for marks. Add summarizingInt for age statistics, and use teeing (Java 12+) to compute the min and max marks in a single pass.Collector using Collector.of that joins non-null strings with a delimiter, prefix and suffix, and caps the output at N items with ... appended. Test it on a sequential and a parallel stream.Set<String> skills field, build Map<Department, Set<String>> of all skills per department using flatMapping. Add filtering to include only employees earning above a threshold, and collectingAndThen to return an unmodifiable map.Transformations
Order objects, each containing a list of LineItem (product, qty, price), use flatMap to compute total revenue, the distinct products sold, and the top 3 products by quantity.flatMap to generate the Cartesian product of two lists, all Pythagorean triples with each side up to 50, and to flatten a Map<String, List<String>> into "key:value" strings.LinkedHashMap and groupingBy), vowel and consonant counts, title-casing every word, and reversing the word order of a sentence.int[][] matrix, use streams to compute row sums, column sums, the transpose, the global maximum, and a flattened sorted array without duplicates.Reduce, Optional and laziness
BigInteger using reduce. Show all three reduce forms, including the combiner version used with parallel streams. Then write Optional<String> emailDomain(Optional<User>) using map, flatMap and filter, with no get() and no null checks.filter, map and limit with peek in between, and print the order in which elements flow through. Show how findFirst and anyMatch short-circuit, and how sorted breaks the one-by-one flow.ArrayList from a parallel forEach and observe the lost or corrupt results. Fix it with collect. Also compare forEach against forEachOrdered on a parallel stream, and run the work in a custom ForkJoinPool, printing the thread names.