Java Assignment- 10

Streams & Pipelines

Basic Questions

  1. Create a stream from List<Integer> nums = Arrays.asList(1,2,3,4,5) and print each number using forEach.
  2. Create a stream from an int[] arr = {2,4,6,8} and print each element. Then convert the stream back to an int[] using toArray.
  3. From List<String> names, use filter to keep only names that start with “A” and collect them into a new List using Collectors.toList().
  4. From List<Integer> nums, use map to square each number and print the results.
  5. From List<String> words = Arrays.asList(“a b”, “c d”, “e”), use flatMap to split by space and produce a stream of single letters, and print them.
  6. Read lines from a file “notes.txt” using Files.lines(Path) and print only lines that are not empty.
  7. Create a stream from a single string using Pattern.compile(“\\s+”) .splitAsStream(“one two three”) and print each token.
  8. Sort a stream of List<String> cities in natural order using sorted() and collect to a List.
  9. Use findFirst() to get the first even number from List<Integer> nums. Print the Optional value safely.
  10. Use anyMatch() to check if any word in List<String> words has length greater than 10 and print true/false.
  11. Use allMatch() to check whether all numbers in List<Integer> nums are positive and print the result.
  12. Use noneMatch() to check that no word equals “error” (case-sensitive) and print the result.
  13. Use count() to print how many strings in List<String> items contain the letter ‘a’.
  14. Use Stream.generate(Math::random) to generate 5 random double values and print them.
  15. Use Stream.iterate(1, n -> n + 2) to generate the first 5 odd numbers and collect them into a List<Integer>.
  16. Create an IntStream from 1..10 and print the sum using sum().
  17. Convert Stream<String> to String[] using toArray(String[]::new) and print the array length.
  18. Map List<String> words to their lengths using mapToInt(String::length) and print the average length using average().
  19. Use Optional with findAny() on a parallel stream of numbers and print the found value or “not found” with orElse.
  20. Compare sequential vs parallel: run Arrays.asList(…large list…) .stream().count() and .parallelStream().count() and print both times in milliseconds (simple System.nanoTime() is fine).

Intermediate Questions

  1. From List<String> lines, remove leading/trailing spaces (map(String::trim)), filter out empty lines, and collect to List<String>.
  2. From List<Integer> nums, filter even numbers, square them, sort descending, and collect to List<Integer>.
  3. Build a Map<String, Integer> from List<String> words where key is the word and value is its length using Collectors.toMap(w -> w, String::length); resolve key clashes by keeping the longer length.
  4. From int[] arr, create an IntStream, use map to triple each value, then convert back to int[] and print the array.
  5. Read “data.csv” with Files.lines, keep only lines containing a comma, split each line by comma, take the first column, and collect to Set<String>.
  6. Use reduce on List<Integer> nums to compute the product of all values and print the result (use identity).
  7. Given List<String> words, use Collectors.joining(“, “) to build a single comma-separated string and print it.
  8. Use distinct() to remove duplicates from a stream of integers and collect to List<Integer>.
  9. Use limit() and skip() on Stream.iterate(1, n -> n + 1) to produce numbers 11..20 and print them.
  10. Using peek(), show each step in a pipeline: start from List<String>, peek before filter, peek after filter, then collect. Print to observe the order.
  11. Use mapToDouble() on List<String> pricesLike “12.5” to parse to doubles; handle bad values by replacing with 0.0 inside the lambda using a small try/catch.
  12. Create a frequency map of words from a sentence (split(“\\s+”)) using Collectors.toMap(w -> w, w -> 1, Integer::sum) and print it.
  13. Use Collectors.groupingBy(String::length) on List<String> words to group words by length; print the resulting Map<Integer, List<String>>.
  14. Use Collectors.partitioningBy(s -> s.length() >= 5) to split List<String> words into two groups; print the map.
  15. From List<Person> (fields: name, age), collect the average age using Collectors.averagingInt(Person::getAge) and print it.
  16. From List<Person>, collect the name of the oldest person using Collectors.maxBy(Comparator.comparingInt(Person::getAge)) and print the Optional.
  17. Implement a small helper static <T> Stream<T> safe(Stream<T> s) that returns an empty stream if s is null; demonstrate avoiding NPE in a pipeline.
  18. Read all file names in a directory using Files.list(Path) and collect them to List<String> of file names (not full paths).
  19. Walk a directory tree with Files.walk(Path) and count how many .txt files exist using a stream pipeline.
  20. Given List<String> dates like “2025-08-27”, validate format YYYY-MM-DD with filter and a regex, and collect only valid strings to a new list.

Advanced Questions

  1. Write a custom collector Collector<String, ?, String> that collects strings into a single String separated by ” | “. Use Collector.of(…) and demonstrate.
  2. Implement a custom Spliterator<Integer> that iterates over even numbers in a given int[]. Wrap it in StreamSupport.stream(…) and print the elements.
  3. Compare sequential vs parallel performance on a CPU-bound task: compute the sum of square roots of numbers 1..10_000_000 using both. Print times and a short note on results.
  4. Show parallel stream pitfalls by mutating a shared ArrayList<Integer> inside forEach on a parallel stream and explain (in comments) why the result is wrong. Then fix it using a thread-safe collector.
  5. Build a file processing pipeline: use Files.lines to read “logs/app.log”, filter lines containing “ERROR”, map to timestamps using substring logic, sort, and write them to “logs/errors.txt” with Files.write (or Files.newBufferedWriter).
  6. Implement an exception-handling helper static <T,R> Function<T,R> wrap(FunctionWithThrow<T,R> f) that catches checked exceptions and rethrows as RuntimeException. Use it to map file paths to file sizes with Files.size(Path) inside a stream.
  7. Create a custom stateful operation safely: use Stream.iterate(new int[]{0,1}, s -> new int[]{s[1], s[0]+s[1]}) to produce the first 10 Fibonacci numbers, map to int, and collect to List<Integer> (no shared mutable state).
  8. Write a pipeline that reads a huge text file, splits into words with flatMap, lowercases, filters out stop words (from a Set<String>), groups by word, and prints the top 10 by frequency (you may use entrySet().stream().sorted(…)).
  9. Implement a custom downstream collector: group people by city and, for each city, collect the three longest names. Use groupingBy(city, collectingAndThen(…)) or mapping(…) + post-processing.
  10. Write a best-practices checklist in comments and code snippets: avoid stateful lambdas, use method references where clear, prefer primitive streams for numeric work, close Stream on I/O (try-with-resources), do not overuse parallel streams (explain when they help), and keep pipelines readable (formatting and naming).