0% found this document useful (0 votes)
53 views35 pages

Java 8 Stream API Insights

The document provides a comprehensive Q&A on Java 8 features, covering key topics such as Lambda Expressions, Functional Interfaces, Stream API, and the new Date and Time API. Each question includes a detailed answer and examples to illustrate the concepts. The document serves as a resource for programmers looking to deepen their understanding of Java 8 functionalities.

Uploaded by

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

Java 8 Stream API Insights

The document provides a comprehensive Q&A on Java 8 features, covering key topics such as Lambda Expressions, Functional Interfaces, Stream API, and the new Date and Time API. Each question includes a detailed answer and examples to illustrate the concepts. The document serves as a resource for programmers looking to deepen their understanding of Java 8 functionalities.

Uploaded by

velocityclass6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

3/27/25, 11:51 AM Java 8 Features Q&A

programming questions and answers on java 8 features

Here are some Java 8 programming questions along with their answers:

1. What are the key features introduced in Java 8?

Answer:

Java 8 introduced several new features, including:

Lambda Expressions

Functional Interfaces

Stream API

Default and Static Methods in Interfaces

Optional Class

New Date and Time API ( [Link] package)

Collectors and Aggregate Operations

Improved Type Inference in Generics

2. What is a lambda expression in Java 8? Give an example.

Answer:

A lambda expression is a concise way to represent an anonymous function. It provides a clear and
concise syntax for writing inline methods.

Example:

java Copy Edit

// Without Lambda Expression interface MyInterface { void show(); } class Test implements
MyInterface { public void show() { [Link]("Hello, Lambda!"); } } // With Lambda
Expression MyInterface obj = () -> [Link]("Hello, Lambda!"); [Link]();

Output:

Copy Edit

Hello, Lambda!

3. What is a functional interface? Give an example.

Answer:

A functional interface is an interface that contains exactly one abstract method but can have multiple
default or static methods. It is used for lambda expressions.

Example:

[Link] 1/35
3/27/25, 11:51 AM Java 8 Features Q&A
java
Copy Edit

@FunctionalInterface interface MyFunctionalInterface { void display(); } public class Test


{ public static void main(String[] args) { MyFunctionalInterface obj = () ->
[Link]("Functional Interface Example"); [Link](); } }

Output:

graphql Copy Edit

Functional Interface Example

Note: Java 8 provides built-in functional interfaces like Predicate , Consumer , Supplier ,
and Function .

4. What is the Stream API in Java 8? How is it different from Collections?

Answer:

The Stream API is introduced in Java 8 to process collections of data in a functional programming style.

Difference Between Streams and Collections:

Feature Collections Streams

Storage Stores elements Does not store elements

Iteration External iteration (for-each loop) Internal iteration (declarative approach)

Modification Can be modified Cannot be modified

Lazy Evaluation No Yes

Example of Stream API:

java Copy Edit

import [Link]; import [Link]; public class StreamExample { public static


void main(String[] args) { List<String> names = [Link]("John", "Mike", "Emma",
"Sara"); [Link]().filter(name -> [Link]("E")).forEach([Link]::println);
} }

Output:

nginx Copy Edit

Emma

5. What are default methods in interfaces? Why were they introduced?

Answer:

Java 8 introduced default methods in interfaces to provide a default implementation without affecting
existing classes that implement the interface.

Example:

java Copy Edit

interface Vehicle { default void start() { [Link]("Vehicle is starting..."); }


} class Car implements Vehicle { } public class DefaultMethodExample { public static void

[Link] 2/35
3/27/25, 11:51 AM Java 8 Features Q&A
main(String[] args) { Car myCar = new Car(); [Link](); // Calls the default method } }

Output:

csharp Copy Edit

Vehicle is starting...

6. What is the Optional class in Java 8? Why is it useful?

Answer:

Optional is a Java 8 feature that helps avoid NullPointerException by providing a container

object that may or may not contain a value.

Example:

java Copy Edit

import [Link]; public class OptionalExample { public static void main(String[]


args) { Optional<String> name = [Link](null);
[Link]([Link]("Default Name")); } }

Output:

pgsql Copy Edit

Default Name

Why Use Optional ?

Avoids NullPointerException

Encourages best practices for handling null values

Provides methods like isPresent() , orElse() , ifPresent()

7. What is the purpose of the Collectors class in Java 8?

Answer:

The Collectors class provides reduction operations like converting streams to lists, sets, or performing
aggregations.

Example:

java Copy Edit

import [Link].*; import [Link]; public class CollectorsExample {


public static void main(String[] args) { List<String> names = [Link]("John", "Mike",
"Emma", "Sara"); List<String> filteredNames = [Link]() .filter(name ->
[Link]("E")) .collect([Link]()); [Link](filteredNames); } }

Output:

csharp Copy Edit

[Emma]

[Link] 3/35
3/27/25, 11:51 AM Java 8 Features Q&A

8. Explain forEach() method in Java 8 with an example.

Answer:

forEach() is a new method introduced in Java 8 that helps iterate over collections in a declarative way.

Example:

java Copy Edit

import [Link]; import [Link]; public class ForEachExample { public static


void main(String[] args) { List<String> names = [Link]("John", "Mike", "Emma",
"Sara"); [Link]([Link]::println); } }

Output:

nginx Copy Edit

John
Mike
Emma
Sara

9. How does the new Date and Time API in Java 8 improve over the old Date
API?

Answer:

Java 8 introduced the [Link] package to replace the old [Link] and [Link] ,
which were mutable and thread-unsafe.

Example Using LocalDate and LocalTime:

java Copy Edit

import [Link]; import [Link]; public class DateTimeExample {


public static void main(String[] args) { LocalDate today = [Link](); LocalTime now =
[Link](); [Link]("Today's Date: " + today); [Link]("Current
Time: " + now); } }

Output:

yaml Copy Edit

Today's Date: 2025-03-27


Current Time: [Link].123

Improvements:

Immutable and Thread-Safe

Better Parsing and Formatting

Support for Time Zones ( ZonedDateTime )

Fluent API for Date Manipulations

[Link] 4/35
3/27/25, 11:51 AM Java 8 Features Q&A

10. How can you use the map() and flatMap() functions in Java 8?

Answer:

map() is used to transform elements, while flatMap() is used when dealing with nested structures.

Example Using map() :

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class MapExample { public static void main(String[] args) { List<String> names =
[Link]("john", "mike", "emma"); List<String> upperCaseNames =
[Link]().map(String::toUpperCase).collect([Link]());
[Link](upperCaseNames); } }

Output:

csharp Copy Edit

[JOHN, MIKE, EMMA]

Example Using flatMap() :

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class FlatMapExample { public static void main(String[] args) { List<List<String>> names =
[Link]( [Link]("John", "Mike"), [Link]("Emma", "Sara") ); List<String>
allNames = [Link]().flatMap(List::stream).collect([Link]());
[Link](allNames); } }

Output:

csharp Copy Edit

[John, Mike, Emma, Sara]

Let me know if you need more questions! 🚀

continue

Here are more Java 8 programming questions and answers to deepen your understanding:

11. What is the difference between findFirst() and findAny() in Streams?

Answer:

Both methods are used to find an element from a Stream:

Method Behavior

findFirst() Returns the first element from the Stream (useful in ordered streams)

findAny() Returns any element from the Stream (optimized for parallel streams)

Example:
[Link] 5/35
3/27/25, 11:51 AM Java 8 Features Q&A

java Copy Edit

import [Link]; import [Link]; import [Link]; public class


FindExample { public static void main(String[] args) { List<String> names =
[Link]("Alice", "Bob", "Charlie", "David"); Optional<String> firstName =
[Link]().findFirst(); Optional<String> anyName = [Link]().findAny();
[Link]("First Name: " + [Link]("Not Found")); [Link]("Any
Name: " + [Link]("Not Found")); } }

Output:

pgsql Copy Edit

First Name: Alice


Any Name: Alice (or any other element in parallel execution)

12. How does the reduce() method work in Java 8?

Answer:

The reduce() method is used to combine elements of a Stream into a single value using an
accumulator function.

Example (Sum of numbers):

java Copy Edit

import [Link]; import [Link]; public class ReduceExample { public static


void main(String[] args) { List<Integer> numbers = [Link](1, 2, 3, 4, 5); int sum =
[Link]().reduce(0, (a, b) -> a + b); [Link]("Sum: " + sum); } }

Output:

makefile Copy Edit

Sum: 15

Other Uses of reduce() :

Find maximum: [Link](Integer::max)

Find minimum: [Link](Integer::min)

Concatenate Strings: [Link]("", String::concat)

13. How does parallelStream() differ from stream() ?

Answer:

stream() : Processes data sequentially (one item at a time).

parallelStream() : Processes data in parallel (multiple threads).

Example Using parallelStream() :

java Copy Edit

import [Link]; import [Link]; public class ParallelStreamExample { public


static void main(String[] args) { List<String> names = [Link]("Alice", "Bob",

[Link] 6/35
3/27/25, 11:51 AM Java 8 Features Q&A
"Charlie", "David"); [Link]().forEach([Link]::println); } }

Output (Order Not Guaranteed):

nginx Copy Edit

Bob
Alice
David
Charlie

When to Use?

Best for large datasets.

Avoid when order matters or when modifying shared resources.

14. What is the purpose of the Predicate functional interface?

Answer:

Predicate<T> is a functional interface that tests a condition and returns true or false .

Example:

java Copy Edit

import [Link]; public class PredicateExample { public static void


main(String[] args) { Predicate<Integer> isEven = num -> num % 2 == 0;
[Link]([Link](10)); // true [Link]([Link](15)); // false
} }

Output:

arduino Copy Edit

true
false

Other Built-in Functional Interfaces:

Interface Function

Predicate<T> Tests a condition ( boolean test(T t) )

Function<T,R> Converts one type to another ( R apply(T t) )

Consumer<T> Performs an action ( void accept(T t) )

Supplier<T> Provides an object ( T get() )

15. How do you use Function functional interface in Java 8?

Answer:

The Function<T, R> interface takes one argument and returns a result.

Example (Converting String to Integer):

java Copy Edit

[Link] 7/35
3/27/25, 11:51 AM Java 8 Features Q&A

import [Link]; public class FunctionExample { public static void


main(String[] args) { Function<String, Integer> lengthFunction = str -> [Link]();
[Link]([Link]("Hello")); // Output: 5 } }

Output:

Copy Edit

16. What is [Link]() in Java 8?

Answer:

Java 8 introduced [Link]() to create comparators in a simpler way.

Example:

java Copy Edit

import [Link]; import [Link]; import [Link]; public class


ComparatorExample { public static void main(String[] args) { List<String> names =
[Link]("Emma", "John", "Alice", "Bob");
[Link]([Link](String::length)); [Link](names); } }

Output (Sorted by String Length):

csharp Copy Edit

[Bob, Emma, John, Alice]

17. What is [Link]() and how does it work?

Answer:

[Link]() is used to group elements in a Stream based on a property.

Example:

java Copy Edit

import [Link].*; import [Link]; class Employee { String name;


String department; Employee(String name, String department) { [Link] = name;
[Link] = department; } } public class GroupingByExample { public static void
main(String[] args) { List<Employee> employees = [Link]( new Employee("Alice",
"HR"), new Employee("Bob", "IT"), new Employee("Charlie", "HR"), new Employee("David",
"IT") ); Map<String, List<Employee>> groupedByDepartment = [Link]()
.collect([Link](emp -> [Link]));
[Link](groupedByDepartment); } }

Output:

Copy Edit

{HR=[Alice, Charlie], IT=[Bob, David]}

[Link] 8/35
3/27/25, 11:51 AM Java 8 Features Q&A

18. What is the peek() method in Streams? How is it different


from forEach() ?

Answer:

peek() : Intermediate operation (used for debugging).

forEach() : Terminal operation (executes on each element).

Example of peek() :

java Copy Edit

import [Link]; import [Link]; public class PeekExample { public static


void main(String[] args) { List<String> names = [Link]("Alice", "Bob", "Charlie");
[Link]() .peek([Link]::println) // Debugging purpose .map(String::toUpperCase)
.forEach([Link]::println); } }

Output:

nginx Copy Edit

Alice
ALICE
Bob
BOB
Charlie
CHARLIE

19. What is Double Colon (::) method reference in Java 8?

Answer:

The :: operator is used to refer to methods without executing them.

Example (Using Static Method Reference):

java Copy Edit

import [Link]; import [Link]; public class MethodReferenceExample {


public static void printName(String name) { [Link](name); } public static void
main(String[] args) { List<String> names = [Link]("Alice", "Bob", "Charlie");
[Link](MethodReferenceExample::printName); } }

Output:

nginx Copy Edit

Alice
Bob
Charlie

These questions will help you master Java 8! Let me know if you need more! 🚀

[Link] 9/35
3/27/25, 11:51 AM Java 8 Features Q&A

continue

Here are more advanced Java 8 interview questions and answers:

20. How do you remove duplicates from a list using Streams?

Answer:

You can use distinct() to remove duplicates in a Stream.

Example:

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class RemoveDuplicates { public static void main(String[] args) { List<Integer> numbers =
[Link](1, 2, 2, 3, 4, 4, 5); List<Integer> uniqueNumbers = [Link]()
.distinct() .collect([Link]()); [Link](uniqueNumbers); } }

Output:

csharp Copy Edit

[1, 2, 3, 4, 5]

21. What is the difference between map() and flatMap() in Streams?

Answer:

Method Purpose

map() Transforms elements individually (one-to-one mapping).

flatMap() Flattens nested structures (one-to-many mapping).

Example Using map() :

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class MapExample { public static void main(String[] args) { List<String> words =
[Link]("hello", "world"); List<List<Character>> mapped = [Link]() .map(word ->
[Link]().mapToObj(c -> (char) c).collect([Link]()))
.collect([Link]()); [Link](mapped); } }

Output:

lua Copy Edit

[[h, e, l, l, o], [w, o, r, l, d]]

Example Using flatMap() :

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class FlatMapExample { public static void main(String[] args) { List<String> words =

[Link] 10/35
3/27/25, 11:51 AM Java 8 Features Q&A
[Link]("hello", "world"); List<Character> flattened = [Link]() .flatMap(word -
> [Link]().mapToObj(c -> (char) c)) .collect([Link]());
[Link](flattened); } }

Output:

csharp Copy Edit

[h, e, l, l, o, w, o, r, l, d]

22. How to convert a List to a Map using Streams?

Answer:

You can use [Link]() to convert a List to a Map.

Example:

java Copy Edit

import [Link].*; import [Link]; class Employee { int id; String


name; Employee(int id, String name) { [Link] = id; [Link] = name; } } public class
ListToMapExample { public static void main(String[] args) { List<Employee> employees =
[Link]( new Employee(1, "Alice"), new Employee(2, "Bob"), new Employee(3, "Charlie")
); Map<Integer, String> employeeMap = [Link]() .collect([Link](emp ->
[Link], emp -> [Link])); [Link](employeeMap); } }

Output:

Copy Edit

{1=Alice, 2=Bob, 3=Charlie}

23. What happens if there are duplicate keys when converting a List to a Map?

Answer:

If duplicate keys exist, [Link]() will throw an IllegalStateException .


To handle duplicates, use the merge function:

Example:

java Copy Edit

import [Link].*; import [Link]; class Employee { int id; String


name; Employee(int id, String name) { [Link] = id; [Link] = name; } } public class
MergeExample { public static void main(String[] args) { List<Employee> employees =
[Link]( new Employee(1, "Alice"), new Employee(2, "Bob"), new Employee(1, "Charlie")
// Duplicate ID ); Map<Integer, String> employeeMap = [Link]()
.collect([Link](emp -> [Link], emp -> [Link], (name1, name2) -> name1 + ", " +
name2)); [Link](employeeMap); } }

Output:

Copy Edit

{1=Alice, Charlie, 2=Bob}

[Link] 11/35
3/27/25, 11:51 AM Java 8 Features Q&A

24. How do you sort a list using Streams?

Answer:

You can use sorted() to sort elements in ascending or descending order.

Example (Ascending Order):

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class SortExample { public static void main(String[] args) { List<Integer> numbers =
[Link](5, 2, 8, 1, 3); List<Integer> sortedNumbers = [Link]() .sorted()
.collect([Link]()); [Link](sortedNumbers); } }

Output:

csharp Copy Edit

[1, 2, 3, 5, 8]

Example (Descending Order):

java Copy Edit

List<Integer> sortedDesc = [Link]() .sorted((a, b) -> b - a)


.collect([Link]());

25. How do you use joining() in Streams?

Answer:

[Link]() is used to concatenate Strings in a Stream.

Example:

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class JoiningExample { public static void main(String[] args) { List<String> words =
[Link]("Hello", "World", "Java"); String joined = [Link]()
.collect([Link](", ")); [Link](joined); } }

Output:

Copy Edit

Hello, World, Java

26. How to filter and limit elements in a Stream?

Answer:

filter() : Selects elements based on a condition.

limit() : Restricts the number of elements.

[Link] 12/35
3/27/25, 11:51 AM Java 8 Features Q&A

Example:

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class FilterLimitExample { public static void main(String[] args) { List<Integer> numbers =
[Link](10, 15, 20, 25, 30); List<Integer> filteredNumbers = [Link]()
.filter(num -> num > 15) .limit(2) .collect([Link]());
[Link](filteredNumbers); } }

Output:

csharp Copy Edit

[20, 25]

27. How do you handle null values safely in Java 8?

Answer:

You can use Optional to avoid NullPointerException .

Example:

java Copy Edit

import [Link]; public class OptionalExample { public static void main(String[]


args) { String name = null; Optional<String> optionalName = [Link](name);
[Link]([Link]("Default Name")); } }

Output:

pgsql Copy Edit

Default Name

28. What is the difference between [Link]() , [Link]() ,


and [Link]() ?

Answer:

Method Behavior

[Link](value) Throws NullPointerException if value is null.

[Link](value) Allows null values safely.

[Link]() Creates an empty Optional.

These are some more Java 8 interview questions with explanations and examples. Let me know if you
need more! 🚀

[Link] 13/35
3/27/25, 11:51 AM Java 8 Features Q&A

continue

Here are more Java 8 interview questions and answers to help you master the concepts! 🚀

29. How does [Link]() work in Java 8?

Answer:

[Link]() is used to generate an infinite sequential Stream based on a given function.

Example (Generate first 5 even numbers):

java Copy Edit

import [Link]; public class StreamIterateExample { public static void


main(String[] args) { [Link](2, n -> n + 2) .limit(5)
.forEach([Link]::println); } }

Output:

Copy Edit

2
4
6
8
10

30. What is [Link]() and how is it different from iterate() ?

Answer:

[Link](seed, UnaryOperator) generates elements based on previous values.

[Link](Supplier) generates elements independently (commonly used for random

values).

Example (Generate 5 random numbers using [Link]() ):

java Copy Edit

import [Link]; import [Link]; public class StreamGenerateExample


{ public static void main(String[] args) { [Link](() -> new Random().nextInt(100))
.limit(5) .forEach([Link]::println); } }

Output (Random Numbers):

Copy Edit

23
67
12
89
44

[Link] 14/35
3/27/25, 11:51 AM Java 8 Features Q&A

31. How do you use [Link]() , allMatch() , and noneMatch() ?

Answer:

These methods are used to check conditions on Stream elements:

Method Description

anyMatch(Predicate) Returns true if at least one element matches.

allMatch(Predicate) Returns true if all elements match.

noneMatch(Predicate) Returns true if no elements match.

Example:

java Copy Edit

import [Link]; import [Link]; public class MatchExample { public static


void main(String[] args) { List<Integer> numbers = [Link](2, 4, 6, 8, 10); boolean
anyMatch = [Link]().anyMatch(n -> n > 8); boolean allMatch =
[Link]().allMatch(n -> n % 2 == 0); boolean noneMatch =
[Link]().noneMatch(n -> n < 0); [Link]("Any match (>8): " + anyMatch);
[Link]("All match (even): " + allMatch); [Link]("None match
(negative): " + noneMatch); } }

Output:

sql Copy Edit

Any match (>8): true


All match (even): true
None match (negative): true

32. How do you perform parallel processing using Java 8 Streams?

Answer:

Use parallelStream() or parallel() to enable parallel execution.

Example:

java Copy Edit

import [Link]; import [Link]; public class ParallelStreamExample { public


static void main(String[] args) { List<String> names = [Link]("Alice", "Bob",
"Charlie", "David"); [Link]() .forEach([Link]::println); // Order not
guaranteed } }

Output (May vary):

nginx Copy Edit

Bob
Alice
David
Charlie

When to use?

Best for large datasets.

[Link] 15/35
3/27/25, 11:51 AM Java 8 Features Q&A

Avoid when order matters.

33. What is [Link]() in Java 8?

Answer:

[Link]() is used to partition elements into two groups (true/false).

Example (Partition numbers into even and odd):

java Copy Edit

import [Link]; import [Link]; import [Link]; import


[Link]; public class PartitioningExample { public static void
main(String[] args) { List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6); Map<Boolean,
List<Integer>> partitioned = [Link]() .collect([Link](n -> n % 2
== 0)); [Link](partitioned); } }

Output:

arduino Copy Edit

{false=[1, 3, 5], true=[2, 4, 6]}

34. What is the difference


between [Link]() and partitioningBy() ?

Answer:

Feature groupingBy() partitioningBy()

Groups Multiple groups Only two groups (true/false)

Return Type Map<K, List<T>> Map<Boolean, List<T>>

Example Group employees by department Partition numbers into even/odd

35. How do you use [Link]() in Java 8?

Answer:

[Link]() provides summary statistics (sum, count, min, max, avg).

Example:

java Copy Edit

import [Link]; import [Link]; import [Link];


import [Link]; public class SummarizingExample { public static void
main(String[] args) { List<Integer> numbers = [Link](10, 20, 30, 40, 50);
IntSummaryStatistics stats = [Link]() .collect([Link](n -> n));
[Link]("Count: " + [Link]()); [Link]("Sum: " +
[Link]()); [Link]("Min: " + [Link]()); [Link]("Max: " +
[Link]()); [Link]("Average: " + [Link]()); } }

Output:

[Link] 16/35
3/27/25, 11:51 AM Java 8 Features Q&A
makefile
Copy Edit

Count: 5
Sum: 150
Min: 10
Max: 50
Average: 30.0

36. What is mapToInt() and when should you use it?

Answer:

mapToInt() converts objects into primitive int Stream ( IntStream ).

It improves performance by avoiding boxing/unboxing.

Example (Find sum of String lengths):

java Copy Edit

import [Link]; import [Link]; public class MapToIntExample { public


static void main(String[] args) { List<String> words = [Link]("Hello", "Java",
"Stream"); int sumLength = [Link]() .mapToInt(String::length) .sum();
[Link]("Total Length: " + sumLength); } }

Output:

mathematica Copy Edit

Total Length: 15

37. What is [Link]() and how do you use it?

Answer:

[Link](stream1, stream2) merges two Streams.

Example:

java Copy Edit

import [Link]; public class StreamConcatExample { public static void


main(String[] args) { Stream<String> stream1 = [Link]("A", "B", "C"); Stream<String>
stream2 = [Link]("D", "E", "F"); Stream<String> combined = [Link](stream1,
stream2); [Link]([Link]::println); } }

Output:

mathematica Copy Edit

A
B
C
D
E
F

[Link] 17/35
3/27/25, 11:51 AM Java 8 Features Q&A

These are some more advanced Java 8 interview questions with explanations and examples. Let me
know if you need more questions or a different topic! 🚀

continue

Here are more Java 8 interview questions and answers covering advanced concepts! 🚀

38. What is the difference between findFirst() and findAny() in Streams?

Answer:

Both methods return an Optional<T> but behave differently in parallel streams:

Method Behavior

findFirst() Returns the first element of the stream (deterministic).

findAny() Returns any element (non-deterministic, faster in parallel).

Example:

java Copy Edit

import [Link]; import [Link]; import [Link]; public class


FindExample { public static void main(String[] args) { List<String> names =
[Link]("Alice", "Bob", "Charlie", "David"); Optional<String> first =
[Link]().findFirst(); Optional<String> any = [Link]().findAny();
[Link]("First: " + [Link]("Not Found")); [Link]("Any: " +
[Link]("Not Found")); } }

Output (May vary in parallel execution):

makefile Copy Edit

First: Alice
Any: Bob (or another random element in parallel mode)

39. What are the default and static methods in Java 8 interfaces?

Answer:

Java 8 introduced default and static methods in interfaces:

Default methods: Methods with implementation inside an interface (can be overridden).

Static methods: Methods inside an interface that cannot be overridden.

Example:

java Copy Edit

interface MyInterface { default void defaultMethod() { [Link]("Default Method


in Interface"); } static void staticMethod() { [Link]("Static Method in
Interface"); } } public class DefaultStaticExample implements MyInterface { public static
void main(String[] args) { DefaultStaticExample obj = new DefaultStaticExample();

[Link] 18/35
3/27/25, 11:51 AM Java 8 Features Q&A
[Link](); // Calls default method [Link](); // Calls static
method } }

Output:

sql Copy Edit

Default Method in Interface


Static Method in Interface

40. Can an interface extend multiple interfaces in Java 8?

Answer:

Yes, an interface can extend multiple interfaces, even if they have default methods.

Example:

java Copy Edit

interface A { default void show() { [Link]("A's show"); } } interface B {


default void show() { [Link]("B's show"); } } interface C extends A, B {
@Override default void show() { [Link](); // Resolving conflict } } public class
MultipleInheritanceExample implements C { public static void main(String[] args) { new
MultipleInheritanceExample().show(); } }

Output:

rust Copy Edit

A's show

If both interfaces have the same method name, we must explicitly resolve the conflict.

41. What is computeIfAbsent() in Java 8's Map interface?

Answer:

computeIfAbsent() computes and inserts a value only if the key is missing.

Example:

java Copy Edit

import [Link]; import [Link]; public class ComputeIfAbsentExample {


public static void main(String[] args) { Map<String, Integer> map = new HashMap<>();
[Link]("A", 10); [Link]("B", k -> 20); // Adds key "B" if absent
[Link]("A", k -> 30); // No effect, "A" exists [Link](map); } }

Output:

Copy Edit

{A=10, B=20}

[Link] 19/35
3/27/25, 11:51 AM Java 8 Features Q&A

42. What is the difference between merge() and putIfAbsent() in Maps?

Answer:

Method Purpose

putIfAbsent(key, value) Inserts a key-value pair only if the key is missing.

merge(key, value, BiFunction) Updates the value if the key exists, otherwise inserts it.

Example:

java Copy Edit

import [Link]; import [Link]; public class MergeExample { public static


void main(String[] args) { Map<String, Integer> map = new HashMap<>(); [Link]("A", 10);
[Link]("A", 20); // No effect, "A" exists [Link]("B", 30); // Adds "B"
[Link]("A", 5, (oldValue, newValue) -> oldValue + newValue); // Adds 5 to existing value
[Link](map); } }

Output:

Copy Edit

{A=15, B=30}

43. How do you use removeIf() in Java 8 Collections?

Answer:

removeIf() removes elements matching a condition from a collection.

Example (Remove all even numbers):

java Copy Edit

import [Link]; import [Link]; public class RemoveIfExample { public


static void main(String[] args) { List<Integer> numbers = new ArrayList<>([Link](1, 2, 3,
4, 5, 6)); [Link](n -> n % 2 == 0); [Link](numbers); } }

Output:

csharp Copy Edit

[1, 3, 5]

44. How does forEach() work on Maps?

Answer:

forEach() iterates over a Map with BiConsumer<K, V> .

Example:

java Copy Edit

import [Link]; import [Link]; public class ForEachMapExample { public


static void main(String[] args) { Map<String, Integer> map = new HashMap<>();

[Link] 20/35
3/27/25, 11:51 AM Java 8 Features Q&A
[Link]("Alice", 25); [Link]("Bob", 30); [Link]((key, value) ->
[Link](key + " is " + value + " years old")); } }

Output:

pgsql Copy Edit

Alice is 25 years old


Bob is 30 years old

45. How does [Link]() work in Java 8?

Answer:

peek() is used for debugging inside a Stream pipeline.

Example:

java Copy Edit

import [Link]; import [Link]; public class PeekExample { public static


void main(String[] args) { List<String> names = [Link]("Alice", "Bob", "Charlie");
[Link]() .peek(name -> [Link]("Processing: " + name))
.map(String::toUpperCase) .forEach([Link]::println); } }

Output:

makefile Copy Edit

Processing: Alice
ALICE
Processing: Bob
BOB
Processing: Charlie
CHARLIE

46. What is the difference between peek() and map() ?

Answer:

Method Purpose

map() Transforms elements and returns a new Stream.

peek() Used for debugging, does not modify elements.

These are some more Java 8 advanced interview questions with explanations and examples. Let me
know if you want more or need explanations on specific topics! 🚀

continue

[Link] 21/35
3/27/25, 11:51 AM Java 8 Features Q&A

Here are even more Java 8 interview questions and answers covering advanced topics! 🚀

47. What is the difference between flatMap() and map() in Streams?

Answer:

Method Purpose

map(Function<T, R>) Transforms elements one-to-one ( T -> R ).

flatMap(Function<T, Stream<R>>) Flattens nested elements ( T -> Stream<R> ).

Example (Using map() )

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class MapExample { public static void main(String[] args) { List<String> words =
[Link]("Hello", "World"); List<Integer> wordLengths = [Link]()
.map(String::length) .collect([Link]()); [Link](wordLengths); //
Output: [5, 5] } }

Example (Using flatMap() )

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class FlatMapExample { public static void main(String[] args) { List<List<Integer>> numbers
= [Link]( [Link](1, 2, 3), [Link](4, 5, 6) ); List<Integer> flatList =
[Link]() .flatMap(List::stream) .collect([Link]());
[Link](flatList); // Output: [1, 2, 3, 4, 5, 6] } }

flatMap() flattens multiple lists into a single stream.

48. What is Optional in Java 8? Why is it used?

Answer:

Optional<T> is a container object that avoids null values.

It helps prevent NullPointerException errors.

Example:

java Copy Edit

import [Link]; public class OptionalExample { public static void main(String[]


args) { Optional<String> name = [Link](null);
[Link]([Link]("Default Name")); // Output: Default Name } }

Use Optional to safely handle missing values.

49. What is the difference between [Link]() , [Link]() ,


and [Link]() ?

Answer:

[Link] 22/35
3/27/25, 11:51 AM Java 8 Features Q&A

Method Description

[Link](value) Throws NullPointerException if value is null .

[Link](value) Returns an empty Optional if value is null .

[Link]() Returns an empty Optional .

Example:

java Copy Edit

Optional<String> nonNull = [Link]("Java"); Optional<String> nullable =


[Link](null); Optional<String> empty = [Link]();
[Link]([Link]("Default")); // Output: Java
[Link]([Link]("Default")); // Output: Default
[Link]([Link]("Default")); // Output: Default

50. How do you filter an Optional value in Java 8?

Answer:

Use .filter(predicate) to apply conditions.

Example (Only allow non-empty strings):

java Copy Edit

import [Link]; public class OptionalFilterExample { public static void


main(String[] args) { Optional<String> name = [Link]("Java"); [Link](n ->
[Link]() > 3) .ifPresent([Link]::println); // Output: Java Optional<String> shortName
= [Link]("Go"); [Link](n -> [Link]() > 3) .ifPresent([Link]::println);
// No Output } }

51. How does [Link]() and [Link]() work?

Answer:

Method Purpose

map(Function<T, R>) Transforms Optional<T> into Optional<R> .

flatMap(Function<T, Optional<R>>) Flattens nested Optional<Optional<R>> into Optional<R> .

Example ( map() vs flatMap() ):

java Copy Edit

import [Link]; public class OptionalMapExample { public static void


main(String[] args) { Optional<String> name = [Link]("Java"); Optional<Integer>
nameLength = [Link](String::length); [Link]([Link]()); // Output: 4
Optional<Optional<Integer>> nestedOptional = [Link](n -> [Link]([Link]()));
[Link]([Link]().get()); // Output: 4 Optional<Integer> flatMapped =
[Link](n -> [Link]([Link]())); [Link]([Link]()); //
Output: 4 } }

flatMap() removes nested Optionals.

[Link] 23/35
3/27/25, 11:51 AM Java 8 Features Q&A

52. What are the Collectors methods in Java 8?

Answer:

The Collectors class provides reduction operations for streams.

Method Purpose

toList() Collect elements into a List<T> .

toSet() Collect elements into a Set<T> .

toMap() Collect elements into a Map<K, V> .

joining(delimiter) Concatenate strings with a delimiter.

groupingBy(classifier) Group elements into a Map<K, List<T>> .

partitioningBy(predicate) Partition elements into true/false groups.

Example (Grouping by length):

java Copy Edit

import [Link]; import [Link]; import [Link]; import


[Link]; public class CollectorsExample { public static void
main(String[] args) { List<String> words = [Link]("Java", "Python", "Go", "C");
Map<Integer, List<String>> groupedByLength = [Link]()
.collect([Link](String::length)); [Link](groupedByLength); } }

Output:

mathematica Copy Edit

{1=[C], 2=[Go], 4=[Java], 6=[Python]}

53. How does [Link]() work?

Answer:

Converts a stream into a Map<K, V> .

Example (Convert List to Map):

java Copy Edit

import [Link]; import [Link]; import [Link]; import


[Link]; public class ToMapExample { public static void main(String[]
args) { List<String> words = [Link]("Java", "Python", "Go"); Map<String, Integer>
wordLengthMap = [Link]() .collect([Link](word -> word, String::length));
[Link](wordLengthMap); } }

Output:

Copy Edit

{Java=4, Python=6, Go=2}

If keys are duplicated, use merge function:

java Copy Edit

.collect([Link](word -> word, String::length, (oldVal, newVal) -> oldVal));

[Link] 24/35
3/27/25, 11:51 AM Java 8 Features Q&A

54. What is reduce() in Java 8 Streams?

Answer:

reduce() combines elements of a stream into a single result.

Example (Find sum of numbers):

java Copy Edit

import [Link]; import [Link]; public class ReduceExample { public static


void main(String[] args) { List<Integer> numbers = [Link](1, 2, 3, 4, 5); int sum =
[Link]() .reduce(0, Integer::sum); [Link]("Sum: " + sum); } }

Output:

makefile Copy Edit

Sum: 15

These are more Java 8 advanced interview questions with detailed explanations and examples! Let me
know if you want more questions or explanations on specific topics. 🚀🔥

continue

Here are even more Java 8 interview questions and answers, covering advanced and tricky topics! 🚀

55. What is the difference between anyMatch() , allMatch() ,


and noneMatch() in Streams?

Answer:

These methods test elements against a predicate and return a boolean result.

Method Description

anyMatch(predicate) Returns true if any element matches the predicate.

allMatch(predicate) Returns true if all elements match the predicate.

noneMatch(predicate) Returns true if no elements match the predicate.

Example:

java Copy Edit

import [Link]; import [Link]; public class MatchExample { public static


void main(String[] args) { List<String> names = [Link]("Alice", "Bob", "Charlie");
boolean anyMatch = [Link]().anyMatch(name -> [Link]("A")); boolean allMatch
= [Link]().allMatch(name -> [Link]() > 2); boolean noneMatch =
[Link]().noneMatch(name -> [Link]("z")); [Link]("anyMatch: " +
anyMatch); // true (Alice starts with 'A') [Link]("allMatch: " + allMatch); //

[Link] 25/35
3/27/25, 11:51 AM Java 8 Features Q&A
true (All names > 2 chars) [Link]("noneMatch: " + noneMatch); // true (No name
ends with 'z') } }

56. What is the difference between unordered() and parallel() in Streams?

Answer:

unordered() removes ordering constraints (useful for optimization).

parallel() enables parallel processing.

Example (Using unordered() for performance boost):

java Copy Edit

import [Link]; import [Link]; public class UnorderedExample { public


static void main(String[] args) { List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);
[Link]() .unordered() // Removes ordering constraints (useful for parallel
processing) .parallel() .forEach([Link]::println); } }

💡 Tip: Use unordered() before parallel() to improve performance.

57. What is the difference between limit() and skip() in Streams?

Answer:

Method Description

limit(n) Returns the first n elements.

skip(n) Skips the first n elements.

Example:

java Copy Edit

import [Link]; import [Link]; public class LimitSkipExample { public


static void main(String[] args) { List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);
[Link]("Limit 3: " + [Link]().limit(3).toList());
[Link]("Skip 3: " + [Link]().skip(3).toList()); } }

Output:

less Copy Edit

Limit 3: [1, 2, 3]
Skip 3: [4, 5, 6]

58. What is [Link]() in Java 8?

Answer:

[Link]() generates an infinite sequential stream.

Example (Generate numbers starting from 1):

[Link] 26/35
3/27/25, 11:51 AM Java 8 Features Q&A
java
Copy Edit

import [Link]; public class IterateExample { public static void


main(String[] args) { [Link](1, n -> n + 2) .limit(5)
.forEach([Link]::println); } }

Output:

Copy Edit

1
3
5
7
9

💡 Tip: Always use limit() to avoid infinite loops!

59. What is the difference between [Link]() and [Link]() ?

Answer:

Method Description

[Link](seed, UnaryOperator<T>) Generates a stream with dependent values.

[Link](Supplier<T>) Generates a stream with independent values.

Example ( generate() to create random numbers):

java Copy Edit

import [Link]; import [Link]; public class GenerateExample {


public static void main(String[] args) { [Link](() -> new Random().nextInt(100))
.limit(5) .forEach([Link]::println); } }

Output (random values):

Copy Edit

23
78
45
99
12

60. How do you sort a List using Java 8 Streams?

Answer:

Use sorted() with a comparator.

Example (Sort names alphabetically and by length):

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class SortExample { public static void main(String[] args) { List<String> names =
[Link]("Alice", "Bob", "Charlie", "Dave"); List<String> sortedNames = [Link]()

[Link] 27/35
3/27/25, 11:51 AM Java 8 Features Q&A
.sorted() .collect([Link]()); List<String> sortedByLength = [Link]()
.sorted((s1, s2) -> [Link]([Link](), [Link]()))
.collect([Link]()); [Link]("Sorted: " + sortedNames);
[Link]("Sorted by Length: " + sortedByLength); } }

Output:

vbnet Copy Edit

Sorted: [Alice, Bob, Charlie, Dave]


Sorted by Length: [Bob, Dave, Alice, Charlie]

61. What is [Link]() in Java 8?

Answer:

Used to apply a function before collecting.

Example (Collect only the lengths of names):

java Copy Edit

import [Link]; import [Link]; import [Link]; import


[Link]; public class MappingExample { public static void main(String[]
args) { List<String> names = [Link]("Alice", "Bob", "Charlie"); Map<Integer,
List<String>> nameLengths = [Link]() .collect([Link](String::length,
[Link](String::toUpperCase, [Link]())));
[Link](nameLengths); } }

Output:

Copy Edit

{3=[BOB], 5=[ALICE], 7=[CHARLIE]}

62. What is teeing() Collector in Java 8?

Answer:

Introduced in Java 12, teeing() combines two collectors.

Example (Find min and max values at the same time):

java Copy Edit

import [Link]; import [Link]; import


[Link]; import [Link]; public class TeeingExample { public
static void main(String[] args) { List<Integer> numbers = [Link](5, 10, 15, 20, 25);
Map<Boolean, Integer> minMax = [Link]() .collect([Link](
[Link](Integer::compareTo), [Link](Integer::compareTo), (min, max) ->
[Link](true, [Link](), false, [Link]()) )); [Link](minMax); } }

Output:

arduino Copy Edit

{true=5, false=25}

[Link] 28/35
3/27/25, 11:51 AM Java 8 Features Q&A

These are more advanced Java 8 interview questions! Want even more tricky questions or real-world
scenarios? Let me know! 🚀🔥

continue

Here are even more Java 8 interview questions and answers, covering tricky scenarios and best
practices! 🚀

63. What is the difference between findFirst() and findAny() in Streams?

Answer:

Method Description

findFirst() Returns the first element from the stream.

findAny() Returns any element (optimized for parallel streams).

Example:

java Copy Edit

import [Link]; import [Link]; import [Link]; public class


FindExample { public static void main(String[] args) { List<String> names =
[Link]("Alice", "Bob", "Charlie", "David"); Optional<String> first =
[Link]().findFirst(); Optional<String> any = [Link]().findAny();
[Link]("findFirst: " + [Link]()); // Output: Alice
[Link]("findAny: " + [Link]()); // Random element in parallel } }

💡 Tip:
Use findFirst() when order matters.

Use findAny() for parallel streams (faster execution).

64. What is the difference between peek() and map() in Streams?

Answer:

Method Purpose

peek() Used for debugging (does not modify elements).

map() Transforms elements.

Example:

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class PeekExample { public static void main(String[] args) { List<String> names =
[Link]("Alice", "Bob", "Charlie"); List<String> processedNames = [Link]()
.peek([Link]::println) // Debugging .map(String::toUpperCase) // Transformation
.collect([Link]()); [Link](processedNames); } }

[Link] 29/35
3/27/25, 11:51 AM Java 8 Features Q&A

💡 Tip: peek() is useful for logging intermediate stream operations.

65. What happens if map() returns null in a Stream?

Answer:

It throws a NullPointerException .

Solution: Use filter() to remove null values.

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class NullMapExample { public static void main(String[] args) { List<String> names =
[Link]("Alice", "Bob", null, "Charlie"); List<String> result = [Link]()
.filter(name -> name != null) // Remove nulls .map(String::toUpperCase)
.collect([Link]()); [Link](result); // Output: [ALICE, BOB, CHARLIE]
} }

💡 Tip: If map() may return null , wrap it with Optional .

66. How does [Link]() work?

Answer:

Combines two streams into one.

Example:

java Copy Edit

import [Link]; public class ConcatExample { public static void


main(String[] args) { Stream<String> first = [Link]("Apple", "Banana"); Stream<String>
second = [Link]("Cherry", "Date"); Stream<String> combined = [Link](first,
second); [Link]([Link]::println); } }

💡 Tip: Streams are consumed once, so do not reuse them.

67. How do you remove duplicates from a Stream?

Answer:

Use .distinct() .

Example:

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class DistinctExample { public static void main(String[] args) { List<Integer> numbers =
[Link](1, 2, 2, 3, 3, 4); List<Integer> uniqueNumbers = [Link]() .distinct()
.collect([Link]()); [Link](uniqueNumbers); // Output: [1, 2, 3, 4] }
}

[Link] 30/35
3/27/25, 11:51 AM Java 8 Features Q&A

68. How do you create a custom collector in Java 8?

Answer:

Use [Link]() .

Example (Joining strings with custom logic):

java Copy Edit

import [Link]; import [Link]; import [Link]; import


[Link]; public class CustomCollectorExample { public static void
main(String[] args) { List<String> words = [Link]("Hello", "World", "Java");
Collector<String, StringBuilder, String> customCollector = [Link](
StringBuilder::new, (sb, word) -> [Link](word).append("-"), StringBuilder::append,
StringBuilder::toString ); String result = [Link]().collect(customCollector);
[Link](result); // Output: Hello-World-Java- } }

69. How do you convert a Stream to an array?

Answer:

Use .toArray() .

Example:

java Copy Edit

import [Link]; public class StreamToArrayExample { public static void


main(String[] args) { String[] words = [Link]("Java", "Python", "C++")
.toArray(String[]::new); [Link](words[0]); // Output: Java } }

70. How do you implement a custom comparator in Java 8?

Answer:

Use [Link]() .

Example (Sort by length, then alphabetically):

java Copy Edit

import [Link]; import [Link]; import [Link]; public class


CustomComparatorExample { public static void main(String[] args) { List<String> names =
[Link]("Bob", "Alice", "Charlie");
[Link]([Link](String::length).thenComparing([Link]()));
[Link](names); // Output: [Bob, Alice, Charlie] } }

71. How do you check if a list contains a specific element using Streams?

Answer:

Use .anyMatch() .

Example:

java

[Link] 31/35
3/27/25, 11:51 AM Java 8 Features Q&A

Copy Edit
import [Link]; import [Link]; public class ContainsExample { public
static void main(String[] args) { List<String> names = [Link]("Alice", "Bob",
"Charlie"); boolean exists = [Link]().anyMatch(name -> [Link]("Bob"));
[Link](exists); // Output: true } }

72. How do you convert a Stream to a Map and handle duplicate keys?

Answer:

Use .toMap() with a merge function.

Example:

java Copy Edit

import [Link]; import [Link]; import [Link]; import


[Link]; public class ToMapExample { public static void main(String[]
args) { List<String> words = [Link]("apple", "banana", "apple", "cherry");
Map<String, Integer> wordCount = [Link]() .collect([Link](word -> word,
word -> 1, Integer::sum)); [Link](wordCount); // Output: {apple=2, banana=1,
cherry=1} } }

These are even more Java 8 advanced interview questions! Let me know if you want tricky edge
cases or real-world use cases! 🚀🔥

continue

You're on fire! 🔥 Here are even more advanced Java 8 interview questions, covering performance
optimizations, tricky scenarios, and best practices! 🚀

73. What is the difference between flatMap() and map() ?

Answer:

Method Purpose

map() Transforms elements one-to-one.

flatMap() Transforms and flattens multiple elements.

Example (Difference Between map() and flatMap() )

java Copy Edit

import [Link]; import [Link]; import [Link]; public


class MapVsFlatMapExample { public static void main(String[] args) { List<List<String>>
namesList = [Link]( [Link]("Alice", "Bob"), [Link]("Charlie", "David")
); // Using map() (List<List<String>> remains) List<List<String>> mappedList =
[Link]() .map(list ->
[Link]().map(String::toUpperCase).collect([Link]()))

[Link] 32/35
3/27/25, 11:51 AM Java 8 Features Q&A
.collect([Link]()); // Using flatMap() (Flattens to List<String>) List<String>
flatMappedList = [Link]() .flatMap(List::stream) .map(String::toUpperCase)
.collect([Link]()); [Link]("map(): " + mappedList);
[Link]("flatMap(): " + flatMappedList); } }

Output:

lua Copy Edit

map(): [[ALICE, BOB], [CHARLIE, DAVID]]


flatMap(): [ALICE, BOB, CHARLIE, DAVID]

💡 Tip: Use flatMap() when dealing with nested collections.

74. What is [Link]() and how does it work?


Answer:
reduce() is used to aggregate elements of a stream.

Example (Sum of numbers using reduce())

java Copy Edit

import [Link]; import [Link]; public class ReduceExample { public static


void main(String[] args) { List<Integer> numbers = [Link](1, 2, 3, 4, 5); int sum =
[Link]() .reduce(0, Integer::sum); // 0 is the identity [Link]("Sum: "
+ sum); // Output: 15 } }

💡 Tip: If the stream is empty, the identity value is returned.

75. How does [Link]() work in Java 9?

Answer:
[Link]() avoids NullPointerException when handling null values.

Before Java 9, filtering null was manual.

Example (Handling null values safely)

java Copy Edit

import [Link]; public class OfNullableExample { public static void


main(String[] args) { [Link](null).forEach([Link]::println); // Does nothing
[Link]("Java").forEach([Link]::println); // Prints "Java" } }

💡 Tip: Before Java 9, use [Link](value).stream() .

76. How do you create an infinite stream?


Answer:
Use [Link]() or [Link]() .

[Link] 33/35
3/27/25, 11:51 AM Java 8 Features Q&A

Example (Generate Fibonacci Sequence)

java Copy Edit

import [Link]; public class FibonacciExample { public static void


main(String[] args) { [Link](new int[]{0, 1}, fib -> new int[]{fib[1], fib[0] +
fib[1]}) .limit(10) .map(fib -> fib[0]) .forEach([Link]::println); } }

Output:

Copy Edit

0 1 1 2 3 5 8 13 21 34

💡 Tip: Always use .limit(n) to avoid infinite loops.

77. What is [Link]() ?


Answer:
It partitions elements into two groups (true/false).

Example (Partition numbers into even and odd)

java Copy Edit

import [Link]; import [Link]; import [Link]; import


[Link]; public class PartitioningExample { public static void
main(String[] args) { List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6); Map<Boolean,
List<Integer>> partitioned = [Link]() .collect([Link](n -> n % 2
== 0)); [Link](partitioned); } }

Output:

arduino Copy Edit

{false=[1, 3, 5], true=[2, 4, 6]}

💡 Tip: Use .partitioningBy() for boolean-based grouping.

78. How do you perform parallel stream processing safely?


Answer:
Use thread-safe operations and avoid shared mutable state.

Example (Parallel Stream with Thread Safety)

java Copy Edit

import [Link]; import [Link]; public class ParallelStreamExample { public


static void main(String[] args) { List<String> names = [Link]("Alice", "Bob",
"Charlie"); [Link]() .map(String::toUpperCase)
.forEachOrdered([Link]::println); } }

💡 Tip: Use .forEachOrdered() to maintain order in parallel streams.

[Link] 34/35
3/27/25, 11:51 AM Java 8 Features Q&A

79. How do you handle exceptions inside Streams?


Answer:
Use .map() with try-catch inside.

Example (Handling checked exceptions in Streams)

java Copy Edit

import [Link]; import [Link]; public class ExceptionHandlingExample {


public static void main(String[] args) { List<String> numbers = [Link]("1", "2",
"three", "4"); [Link]() .map(num -> { try { return [Link](num); } catch
(NumberFormatException e) { return null; // Handle gracefully } })
.forEach([Link]::println); } }

💡 Tip: Use Optional or a custom wrapper for robust handling.

80. How do you measure the performance of a Stream?


Answer:
Use [Link]() or [Link]() .

Example (Measure execution time of a stream)

java Copy Edit

import [Link]; import [Link]; public class


PerformanceExample { public static void main(String[] args) { Instant start =
[Link](); int sum = [Link](1, 1_000_000) .parallel() .sum(); Instant end =
[Link](); [Link]("Sum: " + sum); [Link]("Execution Time: " +
([Link]() - [Link]()) + " ms"); } }

💡 Tip: Parallel Streams improve performance on large datasets.

[Link] 35/35

You might also like