15/04/2025, 11:35 Stream API
Stream API
1. What is the Stream API in Java, and why was it introduced?
The Stream API processes collections in a functional and declarative way, introduced in Java 8 to simplify bulk operations on data
like filtering, mapping, and reducing.
1 List<Integer> numbers = [Link](1, 2, 3);
2 [Link]().filter(n -> n > 1).forEach([Link]::println);
2. How does the Stream API differ from traditional iteration?
Declarative: Focus on "what to do" rather than "how to do".
Lazy Evaluation: Processes elements only when needed.
Parallel Processing: Easily supports concurrent execution.
1 List<String> names = [Link]("Alice", "Bob");
2 [Link]([Link]::println); // Traditional: explicit iteration
3 [Link]().forEach([Link]::println); // Stream: functional style
3. What are the key characteristics of a Stream in Java?
[Link] 1/20
15/04/2025, 11:35 Stream API
Non-Storage: Does not store data.
Lazy Execution: Operations are executed only when required.
Immutability: Original data source is not modified.
Can be Sequential or Parallel.
4. Can you explain the difference between intermediate and terminal operations in Streams?
Intermediate and Terminal Operations
Intermediate Operations:
Transform a stream into another stream.
They are lazy, meaning they do not execute until a terminal operation is invoked.
Examples: filter() , map() , sorted() , distinct() , limit() , skip() .
Terminal Operations:
Trigger the execution of the intermediate operations and produce a result or a side effect.
They are eager, meaning they process the entire stream when invoked.
Examples: collect() , forEach() , reduce() , count() , min() , max() , anyMatch() , allMatch() , noneMatch() .
5. How does the filter() method work in the Stream API?
[Link] 2/20
15/04/2025, 11:35 Stream API
Filters elements based on a predicate.
1 List<String> names = [Link]("Alice", "Bob");
2 [Link]().filter(n -> [Link]("A")).forEach([Link]::println); // Alice
6. What is the purpose of the map() method in Streams?
Transforms elements in a Stream.
1 List<Integer> numbers = [Link](1, 2, 3);
2 [Link]().map(n -> n * 2).forEach([Link]::println); // 2, 4, 6
7. Can you explain the use of the flatMap() method with an example?
Flattens nested structures.
1 List<List<Integer>> lists = [Link]([Link](1, 2), [Link](3, 4));
2 [Link]().flatMap(List::stream).forEach([Link]::println); // 1, 2, 3, 4
8. What are collectors, and how are they used with Streams?
[Link] 3/20
15/04/2025, 11:35 Stream API
Collectors collect and reduce Stream elements into data structures or results.
1 List<Integer> numbers = [Link](1, 2, 3);
2 List<Integer> squared = [Link]().map(n -> n * n).collect([Link]());
9. How can you perform sorting in Streams using sorted() ?
Sorts elements in natural or custom order.
1 List<Integer> numbers = [Link](3, 1, 2);
2 [Link]().sorted().forEach([Link]::println); // 1, 2, 3
10. What is the difference between findFirst() and findAny() in Streams?
findFirst() : Returns the first element.
findAny() : Returns any element (useful in parallel streams).
1 List<Integer> numbers = [Link](1, 2, 3);
2 [Link]([Link]().findFirst().orElse(-1)); // 1
[Link] 4/20
15/04/2025, 11:35 Stream API
11. How does the reduce() method work in the Stream API?
Aggregates elements into a single result.
1 List<Integer> numbers = [Link](1, 2, 3);
2 int sum = [Link]().reduce(0, Integer::sum); // 6
12. What is the purpose of the distinct() method in Streams?
Removes duplicate elements.
1 List<Integer> numbers = [Link](1, 2, 2, 3);
2 [Link]().distinct().forEach([Link]::println); // 1, 2, 3
13. How can you create an infinite Stream in Java?
Use [Link]() or [Link]() .
1 Stream<Integer> infinite = [Link](0, n -> n + 1);
2 [Link](5).forEach([Link]::println); // 0, 1, 2, 3, 4
[Link] 5/20
15/04/2025, 11:35 Stream API
14. What is the role of peek() in debugging Stream operations?
Allows inspection without modifying the Stream.
1 List<Integer> numbers = [Link](1, 2, 3);
2 [Link]().peek([Link]::println).map(n -> n * 2).forEach([Link]::println);
15. How do parallel Streams differ from sequential Streams?
Parallel Streams execute operations concurrently.
1 List<Integer> numbers = [Link](1, 2, 3);
2 [Link]().forEach([Link]::println);
16. What are some common pitfalls of using parallel Streams?
Overhead of thread management.
Thread-safety issues with shared resources.
Inefficient for small datasets.
17. Can you explain the toMap() collector in the Stream API?
[Link] 6/20
15/04/2025, 11:35 Stream API
Converts elements into a Map .
1 List<String> names = [Link]("Alice", "Bob");
2 Map<String, Integer> map = [Link]().collect([Link](n -> n, String::length));
3 [Link](map); // {Alice=5, Bob=3}
18. How do you group elements in a Stream using the groupingBy() collector?
Groups elements by a classifier function.
1 List<String> names = [Link]("Alice", "Bob", "Anna");
2 Map<Character, List<String>> grouped = [Link]()
3 .collect([Link](n -> [Link](0)));
4 [Link](grouped); // {A=[Alice, Anna], B=[Bob]}
19. What is the use of the partitioningBy() collector in Streams?
Partitions elements into two groups based on a predicate.
1 List<Integer> numbers = [Link](1, 2, 3, 4);
2 Map<Boolean, List<Integer>> partitioned = [Link]()
3 .collect([Link](n -> n % 2 == 0));
[Link] 7/20
15/04/2025, 11:35 Stream API
4 [Link](partitioned); // {false=[1, 3], true=[2, 4]}
20. How does short-circuiting work in the Stream API?
Stops processing when the result is determined (e.g., limit , findFirst ).
1 Stream<Integer> numbers = [Link](1, 2, 3, 4);
2 [Link](n -> n > 2).findFirst().ifPresent([Link]::println); // 3
21. Filter vs Map vs Reduce
filter() :
Used to filter elements based on a predicate (condition).
Example:
1 List<Integer> numbers = [Link](1, 2, 3, 4, 5);
2 List<Integer> evenNumbers = [Link]()
3 .filter(n -> n % 2 == 0)
4 .collect([Link]());
map() :
Transforms each element in a stream into another value.
Example:
[Link] 8/20
15/04/2025, 11:35 Stream API
1 List<String> names = [Link]("John", "Jane");
2 List<Integer> nameLengths = [Link]()
3 .map(String::length)
4 .collect([Link]());
reduce() :
Performs aggregation or combines elements of the stream into a single value.
Example:
1 List<Integer> numbers = [Link](1, 2, 3, 4);
2 int sum = [Link]()
3 .reduce(0, Integer::sum);
22. What is Comparator in java?
A Comparator is used to compare two objects for custom sorting.
Example:
1 List<String> names = [Link]("John", "Jane", "Alice");
2 List<String> sortedNames = [Link]()
3 .sorted([Link]())
4 .collect([Link]());
5 // or [Link]() for reverse order
[Link] 9/20
15/04/2025, 11:35 Stream API
23. What is min() and max()?
min() & max()
Find the minimum or maximum element based on a comparator.
Example:
1 List<Integer> numbers = [Link](10, 20, 5, 30);
2 int min = [Link]().min(Integer::compare).orElseThrow();
3 int max = [Link]().max(Integer::compare).orElseThrow();
4
24. What is aggregate ?
Aggregate Operations
Aggregate operations perform calculations such as summation, averaging, or counting.
Example:
1 List<Integer> numbers = [Link](1, 2, 3, 4, 5);
2 int sum = [Link]()
3 .mapToInt(Integer::intValue)
4 .sum();
5 double average = [Link]()
6 .mapToInt(Integer::intValue)
[Link] 10/20
15/04/2025, 11:35 Stream API
7 .average()
8 .orElse(0.0);
9 long count = [Link]().count();
25. Difference between .toList() and collect([Link]())
.toList() :
Introduced in Java 16.
Returns an unmodifiable list.
Example:
1 List<Integer> result = [Link]().toList();
collect([Link]()) :
Available in earlier Java versions.
Returns a modifiable list.
Example:
1 List<Integer> result = [Link]().collect([Link]());
2 [Link](6); // Modifiable
⭐Coding Questions
[Link] 11/20
15/04/2025, 11:35 Stream API
1. Find the First Non-Repeating Character in a String
1 String input = "swiss";
2 Character firstNonRepeating = [Link]()
3 .mapToObj(c -> (char) c)
4 .filter(c -> [Link](c) == [Link](c))
5 .findFirst()
6 .orElse(null);
7 [Link](firstNonRepeating); // Output: 'w'
2. Count Frequency of Elements in a List
1 List<String> items = [Link]("apple", "banana", "apple", "orange", "banana");
2 Map<String, Long> frequencyMap = [Link]()
3 .collect([Link](item -> item, [Link]()));
4 [Link](frequencyMap); // Output: {orange=1, banana=2, apple=2}
3. Find Top-N Highest Numbers in a List
1 List<Integer> numbers = [Link](10, 20, 5, 30, 25);
[Link] 12/20
15/04/2025, 11:35 Stream API
2 int n = 3;
3 List<Integer> topN = [Link]()
4 .sorted([Link]())
5 .limit(n)
6 .collect([Link]());
7 [Link](topN); // Output: [30, 25, 20]
4. Partition a List into Odd and Even Numbers
1 List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);
2 Map<Boolean, List<Integer>> partitioned = [Link]()
3 .collect([Link](n -> n % 2 == 0));
4 [Link](partitioned);
5 // Output: {false=[1, 3, 5], true=[2, 4, 6]}
5. Flatten a List of Lists
1 List<List<Integer>> nestedList = [Link]([Link](1, 2), [Link](3, 4), [Link](5));
2 List<Integer> flatList = [Link]()
3 .flatMap(List::stream)
[Link] 13/20
15/04/2025, 11:35 Stream API
4 .collect([Link]());
5 [Link](flatList); // Output: [1, 2, 3, 4, 5]
6. Find Duplicate Elements in a List
1 First Way
2 List<Integer> numbers = [Link](1, 2, 3, 4, 5, 2, 3);
3 Set<Integer> duplicates = [Link]()
4 .filter(n -> [Link](numbers, n) > 1)
5 .collect([Link]());
6 [Link](duplicates); // Output: [2, 3]
7
//Second Way
8 Set<Integer> set = new LinkedHashSet<>();
9 List<Integer> dup = [Link]().filter(x -> ).toList();
[Link](duplicates);// Output: [2, 3]
7. Sort a List of Custom Objects by Multiple Fields
1 class Person {
[Link] 14/20
15/04/2025, 11:35 Stream API
2 String name;
3 int age;
4 // Constructor, Getters, Setters
5 }
6 List<Person> people = [Link](new Person("John", 25), new Person("Alice", 30), new Person("John", 20));
7 List<Person> sorted = [Link]()
8 .sorted([Link](Person::getName).thenComparing(Person::getAge))
9 .collect([Link]());
10 [Link](p -> [Link]([Link] + " - " + [Link]));
11 // Output: John - 20, John - 25, Alice - 30
8. Calculate the Total Salary of Employees in Each Department
1 Map<String, Double> totalSalaryByDept = [Link]()
2 .collect([Link](
3 Employee::getDepartment,
4 [Link](Employee::getSalary)
5 ));
6 [Link](totalSalaryByDept);
[Link] 15/20
15/04/2025, 11:35 Stream API
9. Filter Strings Starting with a Specific Letter and Collect Them
1 List<String> names = [Link]("Alice", "Bob", "Charlie", "Alex", "Brian");
2 List<String> filtered = [Link]()
3 .filter(name -> [Link]("A"))
4 .collect([Link]());
5 [Link](filtered); // Output: [Alice, Alex]
10. Find the Longest String in a List
1 List<String> strings = [Link]("short", "medium", "longest", "tiny");
2 String longest = [Link]()
3 .max([Link](String::length))
4 .orElse("");
5 [Link](longest); // Output: "longest"
11. Find Common Elements Between Two Lists
1 List<Integer> list1 = [Link](1, 2, 3, 4);
2 List<Integer> list2 = [Link](3, 4, 5, 6);
[Link] 16/20
15/04/2025, 11:35 Stream API
3 List<Integer> common = [Link]()
4 .filter(list2::contains)
5 .collect([Link]());
6 [Link](common); // Output: [3, 4]
12. Find the nth Smallest or Largest Number
1 List<Integer> numbers = [Link](10, 20, 30, 40, 50);
2 int n = 2;
3 int nthLargest = [Link]()
4 .sorted([Link]())
5 .skip(n - 1)
6 .findFirst()
7 .orElseThrow();
8 [Link](nthLargest); // Output: 40
13. Find the First Non-Repeating Character in a String
1 String s1= "sssssHiiiii";
2 Character c1 = [Link]()
[Link] 17/20
15/04/2025, 11:35 Stream API
3 .mapToObj(c -> (char) c)
4 .collect(Collectors
5 .groupingBy(c -> c, LinkedHashMap::new, [Link]()))
6 .entrySet()
7 .stream().filter(entry -> [Link]() == 1)
8 .map([Link]::getKey).findFirst().orElse(null);
9 [Link](c1);
14. Count the Occurrences of Each Character in a String
1 String s1= "sssssHiiiii";
2 Map<Character, Long> collect = [Link]().mapToObj(c -> (char) c)
3 .collect([Link](c -> c, [Link]()));
4 [Link](collect);
15. Find the Sum and Average of a List of Numbers
1 int sum = [Link]().mapToInt(Integer::intValue).sum();
2 OptionalDouble average = [Link]()
3 .mapToInt(Integer::intValue).average();
16. Find the distinct numbers
[Link] 18/20
15/04/2025, 11:35 Stream API
1 List distinctNumbers = [Link]().distinct()
2 .collect([Link]());
Note:
Functional Interface ⟶ interface with single abstract method (i.e Runnable)
Lamba funtion⟶Anonymous function without return type,name,access modifier.
used for implementing functional interface.
i.e
1 Thread t1 = new Thread(()->[Link]("Hi"));
Predicate ⟶Functional interface (Boolean-values function).Used for apply condition
i.e
1 Predicate<Integer> isEven = x->x%2==0;
2 [Link]([Link](3));
Function ⟶Functional interface .Used for doing computation.
Comsumer ⟶ Only take a value;
[Link] 19/20
15/04/2025, 11:35 Stream API
Supplier⟶ Only provide a value (Do not take any value).
Method reference ⟶ use method without invoking & in place of lambda expression
Follow for more such content 🚀✨
[Link] 20/20