Java Stream API Must Read 1747452707
Java Stream API Must Read 1747452707
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.
4. Can you explain the difference between intermediate and terminal operations in Streams?
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() .
7. Can you explain the use of the flatMap() method with an example?
Flattens nested structures.
8. What are collectors, and how are they used with Streams?
Collectors collect and reduce Stream elements into data structures or results.
17. Can you explain the toMap() collector in the Stream API?
Converts elements into a Map .
18. How do you group elements in a Stream using the groupingBy() collector?
Groups elements by a classifier function.
map() :
Transforms each element in a stream into another value.
Example:
1 List<String> names = List.of("John", "Jane");
2 List<Integer> nameLengths = names.stream()
3 .map(String::length)
4 .collect(Collectors.toList());
reduce() :
Performs aggregation or combines elements of the stream into a single value.
Example:
Example:
Aggregate Operations
Aggregate operations perform calculations such as summation, averaging, or counting.
Example:
collect(Collectors.toList()) :
Available in earlier Java versions.
Returns a modifiable list.
Example:
⭐Coding Questions
1. Find the First Non-Repeating Character in a String
1 First Way
2 List<Integer> numbers = List.of(1, 2, 3, 4, 5, 2, 3);
3 Set<Integer> duplicates = numbers.stream()
4 .filter(n -> Collections.frequency(numbers, n) > 1)
5 .collect(Collectors.toSet());
6 System.out.println(duplicates); // Output: [2, 3]
7
//Second Way
8 Set<Integer> set = new LinkedHashSet<>();
9 List<Integer> dup = numbers.stream().filter(x -> !set.add(x)).toList();
System.out.println(duplicates);// Output: [2, 3]
1 class Person {
2 String name;
3 int age;
4 // Constructor, Getters, Setters
5 }
6 List<Person> people = List.of(new Person("John", 25), new Person("Alice", 30), new Person("John", 20));
7 List<Person> sorted = people.stream()
8 .sorted(Comparator.comparing(Person::getName).thenComparing(Person::getAge))
9 .collect(Collectors.toList());
10 sorted.forEach(p -> System.out.println(p.name + " - " + p.age));
11 // Output: John - 20, John - 25, Alice - 30
Note:
i.e
i.e