0% found this document useful (0 votes)
11 views

Java 8 Features Q&A1

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)
11 views

Java 8 Features Q&A1

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
You are on page 1/ 35

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 ( java.time 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() { System.out.println("Hello, Lambda!"); } } // With Lambda
Expression MyInterface obj = () -> System.out.println("Hello, Lambda!"); obj.show();

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:

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 = () ->
System.out.println("Functional Interface Example"); obj.display(); } }

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 java.util.Arrays; import java.util.List; public class StreamExample { public static


void main(String[] args) { List<String> names = Arrays.asList("John", "Mike", "Emma",
"Sara"); names.stream().filter(name -> name.startsWith("E")).forEach(System.out::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() { System.out.println("Vehicle is starting..."); }


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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 2/35
3/27/25, 11:51 AM Java 8 Features Q&A
main(String[] args) { Car myCar = new Car(); myCar.start(); // 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 java.util.Optional; public class OptionalExample { public static void main(String[]


args) { Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("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 java.util.*; import java.util.stream.Collectors; public class CollectorsExample {


public static void main(String[] args) { List<String> names = Arrays.asList("John", "Mike",
"Emma", "Sara"); List<String> filteredNames = names.stream() .filter(name ->
name.startsWith("E")) .collect(Collectors.toList()); System.out.println(filteredNames); } }

Output:

csharp Copy Edit

[Emma]

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; public class ForEachExample { public static


void main(String[] args) { List<String> names = Arrays.asList("John", "Mike", "Emma",
"Sara"); names.forEach(System.out::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 java.time package to replace the old java.util.Date and java.util.Calendar ,
which were mutable and thread-unsafe.

Example Using LocalDate and LocalTime:

java Copy Edit

import java.time.LocalDate; import java.time.LocalTime; public class DateTimeExample {


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

Output:

yaml Copy Edit

Today's Date: 2025-03-27


Current Time: 14:30:15.123

Improvements:

Immutable and Thread-Safe

Better Parsing and Formatting

Support for Time Zones ( ZonedDateTime )

Fluent API for Date Manipulations

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class MapExample { public static void main(String[] args) { List<String> names =
Arrays.asList("john", "mike", "emma"); List<String> upperCaseNames =
names.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(upperCaseNames); } }

Output:

csharp Copy Edit

[JOHN, MIKE, EMMA]

Example Using flatMap() :

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class FlatMapExample { public static void main(String[] args) { List<List<String>> names =
Arrays.asList( Arrays.asList("John", "Mike"), Arrays.asList("Emma", "Sara") ); List<String>
allNames = names.stream().flatMap(List::stream).collect(Collectors.toList());
System.out.println(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:
https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 5/35
3/27/25, 11:51 AM Java 8 Features Q&A

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.Optional; public class


FindExample { public static void main(String[] args) { List<String> names =
Arrays.asList("Alice", "Bob", "Charlie", "David"); Optional<String> firstName =
names.stream().findFirst(); Optional<String> anyName = names.stream().findAny();
System.out.println("First Name: " + firstName.orElse("Not Found")); System.out.println("Any
Name: " + anyName.orElse("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 java.util.Arrays; import java.util.List; public class ReduceExample { public static


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

Output:

makefile Copy Edit

Sum: 15

Other Uses of reduce() :

Find maximum: stream.reduce(Integer::max)

Find minimum: stream.reduce(Integer::min)

Concatenate Strings: stream.reduce("", 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 java.util.Arrays; import java.util.List; public class ParallelStreamExample { public


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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 6/35
3/27/25, 11:51 AM Java 8 Features Q&A
"Charlie", "David"); names.parallelStream().forEach(System.out::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 java.util.function.Predicate; public class PredicateExample { public static void


main(String[] args) { Predicate<Integer> isEven = num -> num % 2 == 0;
System.out.println(isEven.test(10)); // true System.out.println(isEven.test(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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 7/35
3/27/25, 11:51 AM Java 8 Features Q&A

import java.util.function.Function; public class FunctionExample { public static void


main(String[] args) { Function<String, Integer> lengthFunction = str -> str.length();
System.out.println(lengthFunction.apply("Hello")); // Output: 5 } }

Output:

Copy Edit

16. What is Comparator.comparing() in Java 8?

Answer:

Java 8 introduced Comparator.comparing() to create comparators in a simpler way.

Example:

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.Comparator; public class


ComparatorExample { public static void main(String[] args) { List<String> names =
Arrays.asList("Emma", "John", "Alice", "Bob");
names.sort(Comparator.comparing(String::length)); System.out.println(names); } }

Output (Sorted by String Length):

csharp Copy Edit

[Bob, Emma, John, Alice]

17. What is Collectors.groupingBy() and how does it work?

Answer:

Collectors.groupingBy() is used to group elements in a Stream based on a property.

Example:

java Copy Edit

import java.util.*; import java.util.stream.Collectors; class Employee { String name;


String department; Employee(String name, String department) { this.name = name;
this.department = department; } } public class GroupingByExample { public static void
main(String[] args) { List<Employee> employees = Arrays.asList( new Employee("Alice",
"HR"), new Employee("Bob", "IT"), new Employee("Charlie", "HR"), new Employee("David",
"IT") ); Map<String, List<Employee>> groupedByDepartment = employees.stream()
.collect(Collectors.groupingBy(emp -> emp.department));
System.out.println(groupedByDepartment); } }

Output:

Copy Edit

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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; public class PeekExample { public static


void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream() .peek(System.out::println) // Debugging purpose .map(String::toUpperCase)
.forEach(System.out::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 java.util.Arrays; import java.util.List; public class MethodReferenceExample {


public static void printName(String name) { System.out.println(name); } public static void
main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(MethodReferenceExample::printName); } }

Output:

nginx Copy Edit

Alice
Bob
Charlie

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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class RemoveDuplicates { public static void main(String[] args) { List<Integer> numbers =
Arrays.asList(1, 2, 2, 3, 4, 4, 5); List<Integer> uniqueNumbers = numbers.stream()
.distinct() .collect(Collectors.toList()); System.out.println(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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class MapExample { public static void main(String[] args) { List<String> words =
Arrays.asList("hello", "world"); List<List<Character>> mapped = words.stream() .map(word ->
word.chars().mapToObj(c -> (char) c).collect(Collectors.toList()))
.collect(Collectors.toList()); System.out.println(mapped); } }

Output:

lua Copy Edit

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

Example Using flatMap() :

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 10/35
3/27/25, 11:51 AM Java 8 Features Q&A
Arrays.asList("hello", "world"); List<Character> flattened = words.stream() .flatMap(word -
> word.chars().mapToObj(c -> (char) c)) .collect(Collectors.toList());
System.out.println(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 Collectors.toMap() to convert a List to a Map.

Example:

java Copy Edit

import java.util.*; import java.util.stream.Collectors; class Employee { int id; String


name; Employee(int id, String name) { this.id = id; this.name = name; } } public class
ListToMapExample { public static void main(String[] args) { List<Employee> employees =
Arrays.asList( new Employee(1, "Alice"), new Employee(2, "Bob"), new Employee(3, "Charlie")
); Map<Integer, String> employeeMap = employees.stream() .collect(Collectors.toMap(emp ->
emp.id, emp -> emp.name)); System.out.println(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, Collectors.toMap() will throw an IllegalStateException .


To handle duplicates, use the merge function:

Example:

java Copy Edit

import java.util.*; import java.util.stream.Collectors; class Employee { int id; String


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

Output:

Copy Edit

{1=Alice, Charlie, 2=Bob}

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class SortExample { public static void main(String[] args) { List<Integer> numbers =
Arrays.asList(5, 2, 8, 1, 3); List<Integer> sortedNumbers = numbers.stream() .sorted()
.collect(Collectors.toList()); System.out.println(sortedNumbers); } }

Output:

csharp Copy Edit

[1, 2, 3, 5, 8]

Example (Descending Order):

java Copy Edit

List<Integer> sortedDesc = numbers.stream() .sorted((a, b) -> b - a)


.collect(Collectors.toList());

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

Answer:

Collectors.joining() is used to concatenate Strings in a Stream.

Example:

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class JoiningExample { public static void main(String[] args) { List<String> words =
Arrays.asList("Hello", "World", "Java"); String joined = words.stream()
.collect(Collectors.joining(", ")); System.out.println(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.

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 12/35
3/27/25, 11:51 AM Java 8 Features Q&A

Example:

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class FilterLimitExample { public static void main(String[] args) { List<Integer> numbers =
Arrays.asList(10, 15, 20, 25, 30); List<Integer> filteredNumbers = numbers.stream()
.filter(num -> num > 15) .limit(2) .collect(Collectors.toList());
System.out.println(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 java.util.Optional; public class OptionalExample { public static void main(String[]


args) { String name = null; Optional<String> optionalName = Optional.ofNullable(name);
System.out.println(optionalName.orElse("Default Name")); } }

Output:

pgsql Copy Edit

Default Name

28. What is the difference between Optional.of() , Optional.ofNullable() ,


and Optional.empty() ?

Answer:

Method Behavior

Optional.of(value) Throws NullPointerException if value is null.

Optional.ofNullable(value) Allows null values safely.

Optional.empty() Creates an empty Optional.

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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 Stream.iterate() work in Java 8?

Answer:

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

Example (Generate first 5 even numbers):

java Copy Edit

import java.util.stream.Stream; public class StreamIterateExample { public static void


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

Output:

Copy Edit

2
4
6
8
10

30. What is Stream.generate() and how is it different from iterate() ?

Answer:

Stream.iterate(seed, UnaryOperator) generates elements based on previous values.

Stream.generate(Supplier) generates elements independently (commonly used for random

values).

Example (Generate 5 random numbers using Stream.generate() ):

java Copy Edit

import java.util.Random; import java.util.stream.Stream; public class StreamGenerateExample


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

Output (Random Numbers):

Copy Edit

23
67
12
89
44

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 14/35
3/27/25, 11:51 AM Java 8 Features Q&A

31. How do you use Stream.anyMatch() , 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 java.util.Arrays; import java.util.List; public class MatchExample { public static


void main(String[] args) { List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10); boolean
anyMatch = numbers.stream().anyMatch(n -> n > 8); boolean allMatch =
numbers.stream().allMatch(n -> n % 2 == 0); boolean noneMatch =
numbers.stream().noneMatch(n -> n < 0); System.out.println("Any match (>8): " + anyMatch);
System.out.println("All match (even): " + allMatch); System.out.println("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 java.util.Arrays; import java.util.List; public class ParallelStreamExample { public


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

Output (May vary):

nginx Copy Edit

Bob
Alice
David
Charlie

When to use?

Best for large datasets.

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 15/35
3/27/25, 11:51 AM Java 8 Features Q&A

Avoid when order matters.

33. What is Collectors.partitioningBy() in Java 8?

Answer:

Collectors.partitioningBy() is used to partition elements into two groups (true/false).

Example (Partition numbers into even and odd):

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.Map; import


java.util.stream.Collectors; public class PartitioningExample { public static void
main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); Map<Boolean,
List<Integer>> partitioned = numbers.stream() .collect(Collectors.partitioningBy(n -> n % 2
== 0)); System.out.println(partitioned); } }

Output:

arduino Copy Edit

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

34. What is the difference


between Collectors.groupingBy() 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 Collectors.summarizingInt() in Java 8?

Answer:

Collectors.summarizingInt() provides summary statistics (sum, count, min, max, avg).

Example:

java Copy Edit

import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.List;


import java.util.stream.Collectors; public class SummarizingExample { public static void
main(String[] args) { List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);
IntSummaryStatistics stats = numbers.stream() .collect(Collectors.summarizingInt(n -> n));
System.out.println("Count: " + stats.getCount()); System.out.println("Sum: " +
stats.getSum()); System.out.println("Min: " + stats.getMin()); System.out.println("Max: " +
stats.getMax()); System.out.println("Average: " + stats.getAverage()); } }

Output:

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; public class MapToIntExample { public


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

Output:

mathematica Copy Edit

Total Length: 15

37. What is Stream.concat() and how do you use it?

Answer:

Stream.concat(stream1, stream2) merges two Streams.

Example:

java Copy Edit

import java.util.stream.Stream; public class StreamConcatExample { public static void


main(String[] args) { Stream<String> stream1 = Stream.of("A", "B", "C"); Stream<String>
stream2 = Stream.of("D", "E", "F"); Stream<String> combined = Stream.concat(stream1,
stream2); combined.forEach(System.out::println); } }

Output:

mathematica Copy Edit

A
B
C
D
E
F

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; import java.util.Optional; public class


FindExample { public static void main(String[] args) { List<String> names =
Arrays.asList("Alice", "Bob", "Charlie", "David"); Optional<String> first =
names.stream().findFirst(); Optional<String> any = names.parallelStream().findAny();
System.out.println("First: " + first.orElse("Not Found")); System.out.println("Any: " +
any.orElse("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() { System.out.println("Default Method


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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 18/35
3/27/25, 11:51 AM Java 8 Features Q&A
obj.defaultMethod(); // Calls default method MyInterface.staticMethod(); // 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() { System.out.println("A's show"); } } interface B {


default void show() { System.out.println("B's show"); } } interface C extends A, B {
@Override default void show() { A.super.show(); // 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 java.util.HashMap; import java.util.Map; public class ComputeIfAbsentExample {


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

Output:

Copy Edit

{A=10, B=20}

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.HashMap; import java.util.Map; public class MergeExample { public static


void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("A", 10);
map.putIfAbsent("A", 20); // No effect, "A" exists map.putIfAbsent("B", 30); // Adds "B"
map.merge("A", 5, (oldValue, newValue) -> oldValue + newValue); // Adds 5 to existing value
System.out.println(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 java.util.ArrayList; import java.util.List; public class RemoveIfExample { public


static void main(String[] args) { List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3,
4, 5, 6)); numbers.removeIf(n -> n % 2 == 0); System.out.println(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 java.util.HashMap; import java.util.Map; public class ForEachMapExample { public


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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 20/35
3/27/25, 11:51 AM Java 8 Features Q&A
map.put("Alice", 25); map.put("Bob", 30); map.forEach((key, value) ->
System.out.println(key + " is " + value + " years old")); } }

Output:

pgsql Copy Edit

Alice is 25 years old


Bob is 30 years old

45. How does Stream.peek() work in Java 8?

Answer:

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

Example:

java Copy Edit

import java.util.Arrays; import java.util.List; public class PeekExample { public static


void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream() .peek(name -> System.out.println("Processing: " + name))
.map(String::toUpperCase) .forEach(System.out::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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class MapExample { public static void main(String[] args) { List<String> words =
Arrays.asList("Hello", "World"); List<Integer> wordLengths = words.stream()
.map(String::length) .collect(Collectors.toList()); System.out.println(wordLengths); //
Output: [5, 5] } }

Example (Using flatMap() )

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class FlatMapExample { public static void main(String[] args) { List<List<Integer>> numbers
= Arrays.asList( Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6) ); List<Integer> flatList =
numbers.stream() .flatMap(List::stream) .collect(Collectors.toList());
System.out.println(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 java.util.Optional; public class OptionalExample { public static void main(String[]


args) { Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Default Name")); // Output: Default Name } }

Use Optional to safely handle missing values.

49. What is the difference between Optional.of() , Optional.ofNullable() ,


and Optional.empty() ?

Answer:

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 22/35
3/27/25, 11:51 AM Java 8 Features Q&A

Method Description

Optional.of(value) Throws NullPointerException if value is null .

Optional.ofNullable(value) Returns an empty Optional if value is null .

Optional.empty() Returns an empty Optional .

Example:

java Copy Edit

Optional<String> nonNull = Optional.of("Java"); Optional<String> nullable =


Optional.ofNullable(null); Optional<String> empty = Optional.empty();
System.out.println(nonNull.orElse("Default")); // Output: Java
System.out.println(nullable.orElse("Default")); // Output: Default
System.out.println(empty.orElse("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 java.util.Optional; public class OptionalFilterExample { public static void


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

51. How does Optional.map() and Optional.flatMap() 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 java.util.Optional; public class OptionalMapExample { public static void


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

flatMap() removes nested Optionals.

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; import java.util.Map; import


java.util.stream.Collectors; public class CollectorsExample { public static void
main(String[] args) { List<String> words = Arrays.asList("Java", "Python", "Go", "C");
Map<Integer, List<String>> groupedByLength = words.stream()
.collect(Collectors.groupingBy(String::length)); System.out.println(groupedByLength); } }

Output:

mathematica Copy Edit

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

53. How does Collectors.toMap() work?

Answer:

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

Example (Convert List to Map):

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.Map; import


java.util.stream.Collectors; public class ToMapExample { public static void main(String[]
args) { List<String> words = Arrays.asList("Java", "Python", "Go"); Map<String, Integer>
wordLengthMap = words.stream() .collect(Collectors.toMap(word -> word, String::length));
System.out.println(wordLengthMap); } }

Output:

Copy Edit

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

If keys are duplicated, use merge function:

java Copy Edit

.collect(Collectors.toMap(word -> word, String::length, (oldVal, newVal) -> oldVal));

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; public class ReduceExample { public static


void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum =
numbers.stream() .reduce(0, Integer::sum); System.out.println("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 java.util.Arrays; import java.util.List; public class MatchExample { public static


void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
boolean anyMatch = names.stream().anyMatch(name -> name.startsWith("A")); boolean allMatch
= names.stream().allMatch(name -> name.length() > 2); boolean noneMatch =
names.stream().noneMatch(name -> name.endsWith("z")); System.out.println("anyMatch: " +
anyMatch); // true (Alice starts with 'A') System.out.println("allMatch: " + allMatch); //

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 25/35
3/27/25, 11:51 AM Java 8 Features Q&A
true (All names > 2 chars) System.out.println("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 java.util.Arrays; import java.util.List; public class UnorderedExample { public


static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.stream() .unordered() // Removes ordering constraints (useful for parallel
processing) .parallel() .forEach(System.out::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 java.util.Arrays; import java.util.List; public class LimitSkipExample { public


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

Output:

less Copy Edit

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

58. What is Stream.iterate() in Java 8?

Answer:

Stream.iterate() generates an infinite sequential stream.

Example (Generate numbers starting from 1):

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 26/35
3/27/25, 11:51 AM Java 8 Features Q&A
java
Copy Edit

import java.util.stream.Stream; public class IterateExample { public static void


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

Output:

Copy Edit

1
3
5
7
9

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

59. What is the difference between Stream.iterate() and Stream.generate() ?

Answer:

Method Description

Stream.iterate(seed, UnaryOperator<T>) Generates a stream with dependent values.

Stream.generate(Supplier<T>) Generates a stream with independent values.

Example ( generate() to create random numbers):

java Copy Edit

import java.util.Random; import java.util.stream.Stream; public class GenerateExample {


public static void main(String[] args) { Stream.generate(() -> new Random().nextInt(100))
.limit(5) .forEach(System.out::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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 27/35
3/27/25, 11:51 AM Java 8 Features Q&A
.sorted() .collect(Collectors.toList()); List<String> sortedByLength = names.stream()
.sorted((s1, s2) -> Integer.compare(s1.length(), s2.length()))
.collect(Collectors.toList()); System.out.println("Sorted: " + sortedNames);
System.out.println("Sorted by Length: " + sortedByLength); } }

Output:

vbnet Copy Edit

Sorted: [Alice, Bob, Charlie, Dave]


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

61. What is Collectors.mapping() in Java 8?

Answer:

Used to apply a function before collecting.

Example (Collect only the lengths of names):

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.Map; import


java.util.stream.Collectors; public class MappingExample { public static void main(String[]
args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); Map<Integer,
List<String>> nameLengths = names.stream() .collect(Collectors.groupingBy(String::length,
Collectors.mapping(String::toUpperCase, Collectors.toList())));
System.out.println(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 java.util.List; import java.util.stream.Collectors; import


java.util.stream.IntStream; import java.util.Map; public class TeeingExample { public
static void main(String[] args) { List<Integer> numbers = List.of(5, 10, 15, 20, 25);
Map<Boolean, Integer> minMax = numbers.stream() .collect(Collectors.teeing(
Collectors.minBy(Integer::compareTo), Collectors.maxBy(Integer::compareTo), (min, max) ->
Map.of(true, min.get(), false, max.get()) )); System.out.println(minMax); } }

Output:

arduino Copy Edit

{true=5, false=25}

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; import java.util.Optional; public class


FindExample { public static void main(String[] args) { List<String> names =
Arrays.asList("Alice", "Bob", "Charlie", "David"); Optional<String> first =
names.stream().findFirst(); Optional<String> any = names.parallelStream().findAny();
System.out.println("findFirst: " + first.get()); // Output: Alice
System.out.println("findAny: " + any.get()); // 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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


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

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

66. How does Stream.concat() work?

Answer:

Combines two streams into one.

Example:

java Copy Edit

import java.util.stream.Stream; public class ConcatExample { public static void


main(String[] args) { Stream<String> first = Stream.of("Apple", "Banana"); Stream<String>
second = Stream.of("Cherry", "Date"); Stream<String> combined = Stream.concat(first,
second); combined.forEach(System.out::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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


class DistinctExample { public static void main(String[] args) { List<Integer> numbers =
Arrays.asList(1, 2, 2, 3, 3, 4); List<Integer> uniqueNumbers = numbers.stream() .distinct()
.collect(Collectors.toList()); System.out.println(uniqueNumbers); // Output: [1, 2, 3, 4] }
}

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 Collector.of() .

Example (Joining strings with custom logic):

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.stream.Collector; import


java.util.stream.Collectors; public class CustomCollectorExample { public static void
main(String[] args) { List<String> words = Arrays.asList("Hello", "World", "Java");
Collector<String, StringBuilder, String> customCollector = Collector.of(
StringBuilder::new, (sb, word) -> sb.append(word).append("-"), StringBuilder::append,
StringBuilder::toString ); String result = words.stream().collect(customCollector);
System.out.println(result); // Output: Hello-World-Java- } }

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

Answer:

Use .toArray() .

Example:

java Copy Edit

import java.util.stream.Stream; public class StreamToArrayExample { public static void


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

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

Answer:

Use Comparator.comparing() .

Example (Sort by length, then alphabetically):

java Copy Edit

import java.util.Arrays; import java.util.Comparator; import java.util.List; public class


CustomComparatorExample { public static void main(String[] args) { List<String> names =
Arrays.asList("Bob", "Alice", "Charlie");
names.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println(names); // Output: [Bob, Alice, Charlie] } }

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

Answer:

Use .anyMatch() .

Example:

java

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 31/35
3/27/25, 11:51 AM Java 8 Features Q&A

Copy Edit
import java.util.Arrays; import java.util.List; public class ContainsExample { public
static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob",
"Charlie"); boolean exists = names.stream().anyMatch(name -> name.equals("Bob"));
System.out.println(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 java.util.Arrays; import java.util.List; import java.util.Map; import


java.util.stream.Collectors; public class ToMapExample { public static void main(String[]
args) { List<String> words = Arrays.asList("apple", "banana", "apple", "cherry");
Map<String, Integer> wordCount = words.stream() .collect(Collectors.toMap(word -> word,
word -> 1, Integer::sum)); System.out.println(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 java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public


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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 32/35
3/27/25, 11:51 AM Java 8 Features Q&A
.collect(Collectors.toList()); // Using flatMap() (Flattens to List<String>) List<String>
flatMappedList = namesList.stream() .flatMap(List::stream) .map(String::toUpperCase)
.collect(Collectors.toList()); System.out.println("map(): " + mappedList);
System.out.println("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 Stream.reduce() 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 java.util.Arrays; import java.util.List; public class ReduceExample { public static


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

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

75. How does Stream.ofNullable() work in Java 9?

Answer:
Stream.ofNullable() avoids NullPointerException when handling null values.

Before Java 9, filtering null was manual.

Example (Handling null values safely)

java Copy Edit

import java.util.stream.Stream; public class OfNullableExample { public static void


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

💡 Tip: Before Java 9, use Optional.ofNullable(value).stream() .

76. How do you create an infinite stream?


Answer:
Use Stream.generate() or Stream.iterate() .

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 33/35
3/27/25, 11:51 AM Java 8 Features Q&A

Example (Generate Fibonacci Sequence)

java Copy Edit

import java.util.stream.Stream; public class FibonacciExample { public static void


main(String[] args) { Stream.iterate(new int[]{0, 1}, fib -> new int[]{fib[1], fib[0] +
fib[1]}) .limit(10) .map(fib -> fib[0]) .forEach(System.out::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 Collectors.partitioningBy() ?


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

Example (Partition numbers into even and odd)

java Copy Edit

import java.util.Arrays; import java.util.List; import java.util.Map; import


java.util.stream.Collectors; public class PartitioningExample { public static void
main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); Map<Boolean,
List<Integer>> partitioned = numbers.stream() .collect(Collectors.partitioningBy(n -> n % 2
== 0)); System.out.println(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 java.util.Arrays; import java.util.List; public class ParallelStreamExample { public


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

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

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 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 java.util.Arrays; import java.util.List; public class ExceptionHandlingExample {


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

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

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


Answer:
Use System.nanoTime() or Instant.now() .

Example (Measure execution time of a stream)

java Copy Edit

import java.time.Instant; import java.util.stream.IntStream; public class


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

💡 Tip: Parallel Streams improve performance on large datasets.

https://chatgpt.com/c/67e4e69f-07e0-8010-9fcd-19fad96d193c 35/35

You might also like