0% found this document useful (0 votes)
2 views9 pages

java stream -1

The document provides a comprehensive guide on Java Streams, covering their functional programming approach, lazy evaluation, and immutability. It details stream creation methods, intermediate and terminal operations, and includes interview problems with solutions related to finding the second highest number and grouping words by length. Additionally, it discusses performance best practices and advanced problems like finding the highest-paid employees by department.

Uploaded by

Darbar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

java stream -1

The document provides a comprehensive guide on Java Streams, covering their functional programming approach, lazy evaluation, and immutability. It details stream creation methods, intermediate and terminal operations, and includes interview problems with solutions related to finding the second highest number and grouping words by length. Additionally, it discusses performance best practices and advanced problems like finding the highest-paid employees by department.

Uploaded by

Darbar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 9
© Java Streams Complete Interview Preparation Guide # What are Java Streams? 6 Functional Programming approach to process collections e Lazy Evaluation - operations execute only when needed Se Immutable - original collection remains unchanged oe Pipeline Operations - chain multiple operations List names = Arrays.asList("Alice", "Bob", "Charlie"); List result = names.stream() .filter(name -> name.length() > 3) -map (String: :toUpperCase) .collect (Collectors.toList ())i Java Streams Complete Interview Preparation Guide \\ Stream Creation Methods © [From Collectionst) list.stream() @ [From Arrays?) Arrays.stream(array) © Direct Creation?) stream.of(1, 2, 3) © Infinite Streams!) stream.generate(), Stream.iterate() // Prom Collection List nums = Arrays.asList(1, 2, 3); Stream streaml = nums.stream(); // Infinite Stream Stream infinite = Stream.iterate(0, n -> n + 2); © Java Streams Complete Interview Preparation Guide Intermediate Operations @ filter() - Remove elements based on condition © ‘mapO) - Transform each element @ flatMap() - Flatten nested structures numbers.stream() .filter(n -> n % 2 == 0) // Keep even numbers .map(n -> n * 2) // Double each number .distinct() // Remove duplicates .sorted() // Sort ascending .limit(5) // Take first 5 SEVER ety eel Ba maroc ec el} @ Terminal Operations @ collect()) - convert to Collection/Map © forEach()) - Execute action on each element @ Feduce()) - combine elements to single result @ find), mateh(, count()) - search operations // Collect to List List result = stream.collect (Collectors.toList()); // Reduce to sum int sum = numbers. stream().reduce(0, Integer::sum); // Find first match Optional first = names.stream() .filter(name -> name.startsWith("A")) .findFirst(); Ser WER erik eee Bilal mala oy \ Interview Problem #1 Ua gc) Problem: Find the second highest number in a list public static Integer findSecondHighest (List numbers) numbers.stream() .distinct() // Remove duplicates { return .sorted (Collections.reverseOrder()) // Sort descending .skip(1) // Skip first (highest) .findFirst() // Get second .orElse (null); case } // Test List nums // Handle empty Arrays.asList(1, 3, 4, 5, 5, 6, 9% 9)7 Integer result = findSecondHighest (nums); // Returns: 6 Key Concepts: distinct(), sorted(), skip(), Optional handling Come Ema rT Complete Interview Preparation Guide \ Interview Problem #2 GROUPING & COUNTING Problem: Group words by length and count occurrences public static Map countByLength(List words) { return words.stream() .collect (Collectors .groupingBy( String ength, // Group by length Collectors.counting() // Count in each group )); } // Test List words = Arrays.asList ("apple", "banana", “cat", “dog"); Map result = countByLength(words); // Result: (3-2, 5-2} (2 words of length 3, 2 words of length 5) Key Concepts: groupingBy(), counting(), method references © Java Streams Ce BU amc ancl] oly ® Advanced Problem Problem: Find employees with highest salary by department class Employee { private String name, department; private double salary; // constructors, getters... } public static Map> findHighestPaidByDept (List employees) { return employees. stream() -collect (Collectors.groupingBy( Employee: :getDepartment, Collectors.maxBy ( Comparator .comparing (Employee etSalary) )} )); } Key Concepts: Complex grouping, maxBy(), Comparator Sr rye age Cela mato eumell eo} % Performance & Best Practices © Parallel Streams!) Use for large datasets (>10k elements) 0 “Avoid: Modifying source during operations © ‘Remember: streams can only be used once © (Optional! Handle properly with orElse/orElseGet // Parallel Stream (for large datasets) List bighist = // ... large dataset long sum = bigList.parallelstream() .mapToLong (Integer: :longValue) -sum(); // Handle Optional properly Optional result = names.stream() -filter(name -> name.startsWith("Z")) .findFirst(); String name = result.orElse ("Default Name"); © Java Streams Complete Interview Preparation Guide & flatMap() Deep Dive Problem: Flatten nested collections // Nested Lists List> nestedbists = Arrays.asbist ( Arrays.asbist ("a", "b"), Arrays.asList("c", "d", "e"), Arrays.asbist("£") ); // Flatten using flatMap List flattened = nestedLists.stream() -flatMap (Collection::stream) // Flatten each inner list -collect (Collectors.tobist()); // Result: [a, by c, dy e, f] // vs map() - would give Stream> // flatMap() gives Stream Key Point: map() = 1-to-1, flatMap() = 1-to-many

You might also like