============================================================ IT6003 - Advanced Java Programming Lab Session 3: Stream API State University of Zanzibar (SUZA) ============================================================ OBJECTIVES: - Create streams from various sources - Apply intermediate operations (filter, map, sorted, distinct, flatMap) - Apply terminal operations (collect, reduce, forEach, count, findFirst) - Use Collectors for grouping, partitioning, joining, and summarizing - Understand parallel streams ============================================================ PART A: Creating and Basic Streams [30 minutes] ============================================================ Exercise 1: Creating Streams ------------------------------ a) From a List: list.stream() b) From an array: Arrays.stream(arr) c) From values: Stream.of(1, 2, 3, 4, 5) d) From a range: IntStream.range(1, 11) and IntStream.rangeClosed(1, 10) e) Infinite stream: Stream.iterate(0, n -> n + 2).limit(10) // first 10 even numbers f) Generate: Stream.generate(Math::random).limit(5) Exercise 2: Filter and Map ----------------------------- Given: List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20, 25); a) Filter even numbers and print them. b) Filter numbers greater than 10. c) Map each number to its square. d) Filter even numbers, then map to their squares, then collect to list. e) Map to String: convert each number to "Number: X". Exercise 3: Sorting and Distinct ----------------------------------- Given: List words = Arrays.asList("banana", "apple", "cherry", "apple", "date", "banana", "elderberry"); a) Get distinct words. b) Sort alphabetically. c) Sort by string length. d) Sort by length descending, then alphabetically for same length. e) Get the first 3 shortest unique words. ============================================================ PART B: Terminal Operations [30 minutes] ============================================================ Exercise 4: Reduce -------------------- Given: List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); a) Find the sum using reduce(0, Integer::sum). b) Find the product using reduce(1, (a, b) -> a * b). c) Find the maximum using reduce(Integer::max). d) Concatenate a list of strings using reduce("", String::concat). e) Calculate factorial of 10 using IntStream.rangeClosed(1, 10).reduce(1, (a, b) -> a * b). Exercise 5: Collecting Results --------------------------------- Given a list of Student objects (name, department, gpa): a) Collect names to List using Collectors.toList(). b) Collect names to Set using Collectors.toSet(). c) Collect to Map (name -> gpa) using Collectors.toMap(). d) Join names with comma: Collectors.joining(", "). e) Count students: Collectors.counting(). f) Find average GPA: Collectors.averagingDouble(Student::getGpa). g) Summarize GPA: Collectors.summarizingDouble(Student::getGpa). Exercise 6: Find and Match ----------------------------- a) findFirst(): first student with GPA > 3.5 b) findAny(): any student from CS department c) anyMatch(): is there any student with GPA = 4.0? d) allMatch(): do all students have GPA > 2.0? e) noneMatch(): no student has GPA below 1.0? f) count(): how many students in IT department? ============================================================ PART C: Advanced Collectors [30 minutes] ============================================================ Exercise 7: Grouping ----------------------- Given 15+ students with departments (CS, IT, IS, NET): a) Group students by department: Collectors.groupingBy(Student::getDepartment) Result: Map> b) Count per department: groupingBy(dept, counting()) Result: Map c) Average GPA per department: groupingBy(dept, averagingDouble(gpa)) d) Max GPA per department: groupingBy(dept, maxBy(comparingDouble(gpa))) e) Names per department: groupingBy(dept, mapping(name, toList())) Exercise 8: Partitioning --------------------------- a) Partition students into GPA >= 3.0 and GPA < 3.0. Result: Map> b) Count in each partition. c) Partition then group by department within each partition. Exercise 9: FlatMap --------------------- a) Given List> = [[1,2,3], [4,5], [6,7,8,9]] Flatten to [1,2,3,4,5,6,7,8,9] using flatMap. b) Given List sentences, split each into words and get all unique words. c) Given Map> (dept -> students), get a flat list of all students. ============================================================ PART D: Parallel Streams and Real-World [30 minutes] ============================================================ Exercise 10: Parallel Streams -------------------------------- a) Create a list of 1,000,000 random integers. b) Find sum using sequential stream. Measure time with System.nanoTime(). c) Find sum using parallel stream. Measure time. d) Compare the times. Print results. e) Note: parallel streams use ForkJoinPool, good for CPU-intensive tasks. Exercise 11: CSV File Processing with Streams ------------------------------------------------ Create a file "students.csv" with 20 rows: RegNo,Name,Department,GPA SUZA001,Ali Hassan,CS,3.5 SUZA002,Fatma Omar,IT,3.8 ... a) Read the file using Files.lines() to create a stream. b) Skip the header line using skip(1). c) Parse each line into a Student object using map(). d) Filter students with GPA > 3.0. e) Group by department. f) Find the top 3 students by GPA. g) Write results to "report.txt". Exercise 12: Stream Pipeline Challenge ----------------------------------------- Given a text file with 100+ words: a) Read all words from the file. b) Convert to lowercase. c) Remove punctuation. d) Filter out common words (the, a, an, is, are, was, were). e) Count frequency of each remaining word. f) Sort by frequency descending. g) Display top 10 most frequent words as a formatted table. h) Calculate total unique words and total word count. ============================================================ SUBMISSION: Submit all .java files in a folder named Lab03_RegNo/ ============================================================