Top 75+ Java 8 Interview Questions and Answers

Updated on September 16, 2024

Article Outline

Are you getting ready for a job that demands Java skills? If yes, it’s important to grasp the features and improvements in Java 8 for your success, in the role ahead. Java 8 is extensively utilised across organisations at this time and being well-informed about its new functionalities and upgrades could give you confidence during interviews and increase your ability to manage contemporary Java applications effectively.

 

In this blog post, we’re going to cover a range of Java 8 interview questions, for newcomers as well as experienced professionals alike! The list includes a mix of complex questions that cover concepts and practical coding challenges to help you get ready for your upcoming interview, with confidence.

What is Java 8?

Java 8 marked a milestone for the Java programming language, with its launch in March 2014. It introduced new features that enhanced its strength and adaptability to meet present-day programming requirements better. Essential elements such as Lambda expressions and the Stream API, alongside the revamped Date Time API, empowered programmers to write code that’s not only more efficient but also more succinct and functional.

 

Java 8 also brought in some other improvements like the Optional class for handling null values better and default and static methods in interfaces along with the Nashorn JavaScript engine. These updates really made Java 8 an effective language for developers, providing performance and memory management while also making it easier to blend with various programming styles seamlessly. Developers still favour Java 8 for its mix of capabilities and reliability, in their work.

 

Also Read: Java Full Stack Developer Salary

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Java 8 Interview Questions for Freshers

What features do you know or use in Java 8?

Java 8 introduced several new features that significantly changed how developers write code:

  • Lambda Expressions: Allows functionality to be treated as a method argument or code as data.
  • Stream API: Provides a way to process collections of objects using functional programming.
  • Optional Class: Helps in avoiding null checks and NullPointerExceptions.
  • Date-Time API: Offers a new set of date and time APIs for handling date-related tasks.
  • Default and Static Methods in Interfaces: Allows methods with a body in interfaces.
  • Nashorn JavaScript Engine: Enables embedding JavaScript in Java applications.
  • Collectors and Enhanced Collections Framework: Supports efficient data manipulation.

In which programming paradigm did Java 8 fall?

Java 8 is mainly categorised under Object Oriented Programming (OÖP). It also incorporates concepts from Functional Programming (FP). Through features such as Lambda expressions and the Stream APÏ, Java 8 allows developers to write code in a more functional style, combining both paradigms to leverage the benefits of each.

What is Stream API in Java 8?

The Stream API in Java 8 is a powerful feature that allows developers to process collections of objects in a functional style. It enables operations like filtering, mapping, and reducing data in a declarative way. Streams provide a sequence of elements that support many operations, such as:

  • Intermediate Operations: map(), filter(), sorted()
  • Terminal Operations: collect(), forEach(), reduce()

The Stream API promotes better readability and allows for parallel execution, making data processing tasks more efficient.

 

Also Read: Difference Between ArrayList and LinkedList in Java

What is the difference between anyMatch and allMatch in Stream?

Method Description Returns
anyMatch Returns true if any element in the stream matches the given predicate. boolean
allMatch Returns true if all elements in the stream match the given predicate. boolean

What is Lambda Expression?

Lambda Expressions in Java 8 provide a way to write anonymous functions. They enable treating functionality as a method argument and allow writing more concise and readable code.

 

The syntax is:

 

(parameters) -> expression

 

For example:

 

(List<String> names) -> names.forEach(System.out::println);

 

In the above example, we pass a ‘names’ list of strings as a parameter of the function and traverse the string list in the function body.

 

Lambda Expressions are often used in combination with the Stream API and functional interfaces like Runnable, Callable, Comparator, etc.

What are the various categories of pre-defined Function Interfaces?

Interface Description Method Signature
Predicate Represents a boolean-valued function of one argument. boolean test(T t)
Function Represents a function that accepts one argument and produces a result. R apply(T t)
Consumer Represents an operation that accepts a single input argument and returns no result. void accept(T t)
Supplier Represents a supplier of results with no input. T get()
BiFunction Represents a function that accepts two arguments and produces a result. R apply(T t, U u)

Write a Java 8 program to print 5 random numbers using forEach.

Here’s a simple Java 8 program that generates and prints 5 random numbers using the forEach method:

import java.util.Random; import java.util.stream.Stream;   public class RandomNumbers { public static void main(String[] args) { Stream.generate(new Random()::nextInt) .limit(5) .forEach(System.out::println); } }

How do map, filter, and reduce operations differ in Stream API?

Operation Purpose Input Output Example
map Transforms each element in a stream to another form. Stream<T> Stream<R> (transformed) Convert each character of the string to uppercase.
filter Selects elements based on a condition. Stream<T> Stream<T> (filtered) Filter numbers greater than 10.
reduce Combines elements to produce a single result. Stream<T> Optional<T> or any type Sum all numbers given in the list.

What is a Functional Interface in Java 8?

A Functional Interface is an interface with a single abstract method, also known as a Single Abstract Method (SAM) interface. It can have multiple default or static methods but only one abstract method. Functional interfaces are the basis for Lambda Expressions in Java 8.

 

Examples of functional interfaces:

 

  • Runnable
  • Callable
  • Comparator
  • Function

Write a Java 8 program to remove duplicates from a list of integers.

Here is a Java 8 program that removes duplicates from a list of integers using the Stream API:

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> distinctNumbers = numbers.stream() .distinct() .collect(Collectors.toList()); System.out.println(distinctNumbers); } }

What is the purpose of the Predicate Interface in Java 8?

The Predicate Interface represents a boolean-valued function of one argument. It is used primarily for evaluating a condition or criteria, such as filtering collections or streams. It contains the test(T t) method, which returns true or false based on the condition provided.

 

Common use cases:

 

  • Filtering data using filter().
  • Conditional checks in various operations.

What are the main components of a Stream?

Component Description
Source The data source (e.g., collections, arrays) that provides the stream elements.
Intermediate Operations Operations that transform a stream into another stream, such as map(), filter().
Terminal Operations Operations that produce a result or side effect, like collect(), forEach().

What is the difference between findFirst() and findAny()?

Method Description Usage
findFirst() Returns the first element in the stream. Used when order matters.
findAny() Returns any element from the stream, which may not be the first in parallel streams. Used for parallel processing.

What is the purpose of the BiFunction Interface in Java 8?

The BiFunction Interface represents a function that takes two arguments and produces a result. It serves as an interface, with the method R apply(T t, U u) where T and U represent input types and R signifies the output type. It proves valuable for tasks demanding two input values to yield an output, such, as adding two numbers or joining two strings.

Write a Java 8 program to sort a list of employees by their age using Lambda Expression.

import java.util.Arrays; import java.util.List; class Employee { String name; int age; Employee(String name, int age) { this.name = name; this.age = age; }   @Override public String toString() { return name + " (" + age + ")"; } }   public class SortEmployees { public static void main(String[] args) { List<Employee> employees = Arrays.asList( new Employee("Alice", 30), new Employee("Bob", 25), new Employee("Charlie", 35) );   // Sort employees by age using Lambda Expression employees.sort((e1, e2) -> Integer.compare(e1.age, e2.age));   // Print sorted employee list employees.forEach(System.out::println); } }

How do the Stream methods sorted(), distinct(), and limit() differ?

 

Method Purpose Input Output
sorted() Sorts the elements of the stream according to a comparator. Stream<T> Stream<T> (sorted)
distinct() Removes duplicate elements from the stream. Stream<T> Stream<T> (unique)
limit() Truncates the stream to a given number of elements. Stream<T> Stream<T> (limited)

 

What is the Date-Time API in Java 8?

The Date-Time API in Java 8 provides a comprehensive set of date and time handling features through java.time package. It replaces the old Date and Calendar classes with more accurate and easier-to-use classes such as LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant, and Duration. These classes are immutable and thread-safe, promoting cleaner and safer code.

Write a Java 8 program to convert a list of strings to uppercase.

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

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ConvertToUpperCase { public static void main(String[] args) { List<String> words = Arrays.asList("java", "stream", "lambda"); // Convert each string in the list to uppercase using Stream API List<String> upperCaseWords = words.stream() .map(String::toUpperCase) .collect(Collectors.toList()); // Print the converted list System.out.println(upperCaseWords); } }

How does the Date-Time API differ from the old Date and Calendar API in Java?

 

Feature Date-Time API (Java 8) Old Date and Calendar API
Immutability Immutable classes (LocalDate, LocalTime, etc.) Mutable classes (Date, Calendar)
Thread Safety Thread-safe Not thread-safe
Easy to Use More readable and method chaining Complex and verbose
Time Zone Handling ZonedDateTime, OffsetDateTime for better support Limited and complex

 

What is the difference between Optional and null handling in Java?

 

Feature Optional Null
Safety Prevents NullPointerException Can cause NullPointerException
Methods Provides methods like isPresent(), orElse() No methods available
Usage Explicitly checks presence of value Requires manual null checks
Functionality Encourages functional programming No support for functional style

 

Explain with examples, LocalDate, LocalTime, and LocalDateTime APIs.

 

    • LocalDate: Represents a date without a time-zone in ISO-8601 calendar system.

 

LocalDate today = LocalDate.now(); // Current date   LocalDate birthDate = LocalDate.of(1995, Month.JUNE, 25); // Specific date

    • LocalTime: Represents a time without a time-zone in ISO-8601 format.

 

LocalTime now = LocalTime.now(); // Current time LocalTime lunchTime = LocalTime.of(12, 30); // Specific time

    • LocalDateTime: Combines date and time without a time-zone.

 

LocalDateTime meetingTime = LocalDateTime.of(today, lunchTime); // Combining date and time

Write a Java 8 program to check if a given string is a palindrome or not.

public class PalindromeCheck { public static void main(String[] args) { String input = "madam";   // Check if the string is a palindrome boolean isPalindrome = input.equals(new StringBuilder(input).reverse().toString());   // Print result System.out.println("Is " + input + " a palindrome? " + isPalindrome); } }

What is the use of JJS in Java 8?

JJS is a command-line tool used in Java 8 to execute JavaScript code. It leverages the Nashorn JavaScript engine, allowing developers to run JavaScript from within the Java environment. This tool is useful for scripting tasks and allows seamless integration of Java and JavaScript.

What are the differences between the forEach() and forEachOrdered() methods in Java Streams?

 

Method Description Order Guarantee
forEach() Performs an action for each element in the stream. No guaranteed order
forEachOrdered() Performs an action for each element in the encounter order of stream. Maintains encounter order

Write a Java 8 program to find the second-highest number in a list of integers.

import java.util.Arrays; import java.util.List; import java.util.Optional;   public class SecondHighestNumber { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 3, 4, 5, 6, 6, 7, 8);   // Find the second-highest number using Stream API Optional<Integer> secondHighest = numbers.stream() .distinct() // Remove duplicates .sorted((a, b) -> b - a) // Sort in descending order .skip(1) // Skip the first (highest) number .findFirst(); // Find the second-highest number   // Print the result secondHighest.ifPresent(num -> System.out.println("The second-highest number is: " + num)); } }

How do Functional Interfaces differ from traditional interfaces?

 

Feature Functional Interfaces Traditional Interfaces
Method Count Only one abstract method (SAM) Can have multiple abstract methods
Lambda Support Supports Lambda Expressions Does not support Lambdas directly
Usage Primarily for functional-style programming General-purpose, multiple method contracts
Example Interfaces Runnable, Callable, Comparator List, Set, Map

 

What are Intermediate and Terminal Operations?

Type of Operation Description Example Methods
Intermediate Operations Operations that transform a stream into another stream and are lazy (not executed until terminal operation is called). filter(), map(), sorted()
Terminal Operations Operations that produce a result or a side-effect, completing the stream pipeline. forEach(), collect(), reduce()

 

What are static methods in Interfaces?

Static methods in interfaces are methods defined with the static keyword. They belong to the interface itself and cannot be overridden by implementing classes. Static methods are useful for providing utility functions that are related to the interface.

 

Example:

 

interface Utility { static int add(int a, int b) { return a + b; } }

Write a Java 8 program to filter out the even numbers from a list of integers.

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;   public class FilterEvenNumbers { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);   // Filter out even numbers using Stream API List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList());   // Print the even numbers System.out.println(evenNumbers); } }

What is the purpose of the limit() method in Java 8?

In Java 8, the limit() function is employed to cut down a stream so that it only holds a number of elements not exceeding the specified number. It is an intermediate operation and is commonly used to create sublists, manage the number of items processed, or control memory usage.

What is the difference between limit and skip?

Method Purpose Example Usage
limit(n) Limits the stream to the first n elements. stream.limit(5) to get the first 5 elements.
skip(n) Skips the first n elements of the stream. stream.skip(3) to ignore the first 3 elements.

What are the default methods in Java 8?

Default methods in Java 8 are methods defined with the default keyword inside an interface. They provide a method implementation that can be inherited by classes implementing the interface, allowing interfaces to evolve without breaking existing implementations.

 

Example:

 

interface Vehicle { default void print() { System.out.println(“I am a vehicle”); } }

Write a Java 8 program to find the maximum value in a list of integers using Stream API.

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

import java.util.Arrays; import java.util.List; import java.util.Optional;   public class MaxValue { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 3, 7, 2, 8, 5);   // Find the maximum value using Stream API Optional<Integer> max = numbers.stream() .max(Integer::compareTo);   // Print the maximum value max.ifPresent(value -> System.out.println("The maximum value is: " + value)); } }

What is the main advantage of Stream API?

The Stream API offers a benefit by enabling developers to handle data collections in a user-friendly manner while ensuring efficiency and readability, in their code structure.

What is the difference between a map and a filter in Stream API?

 

Method Purpose Output
map() Transforms each element in the stream to another form. Stream with transformed elements
filter() Selects elements based on a condition. Stream with filtered elements

 

Write a Java 8 program to group a list of students by their grades using Streams.

import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; class Student { String name; String grade; Student(String name, String grade) { this.name = name; this.grade = grade; } public String getGrade() { return grade; } @Override public String toString() { return name; } } public class GroupStudents { public static void main(String[] args) { List<Student> students = Arrays.asList( new Student("Alice", "A"), new Student("Bob", "B"), new Student("Charlie", "A"), new Student("Dave", "B"), new Student("Eve", "C") ); // Group students by their grades Map<String, List<Student>> groupedByGrade = students.stream() .collect(Collectors.groupingBy(Student::getGrade)); // Print the grouped students groupedByGrade.forEach((grade, studentList) -> System.out.println(grade + ": " + studentList)); } }

What is the Java 8 StringJoiner class used for?

In Java 8, the StringJoiner class is used to construct a string of characters separated by a chosen delimiter with the option to start with a specified prefix and end with a suffix, making the string concatenation process more efficient and organised.

Example:

StringJoiner joiner = new StringJoiner(“, “, “[“, “]”); joiner.add(“Java”).add(“Python”).add(“C++”); System.out.println(joiner); // Output: [Java, Python, C++]

What are the two types of streams offered by Java 8?

Stream Type Description
Sequential Stream Processes elements in the order they are in the source, single-threaded.
Parallel Stream Splits the content into sections and handles them simultaneously in parallel threads.

 

What sets stream() apart, from parallelStream()?

Method Description Processing Model
stream() Creates a sequential stream that processes elements in a single-threaded mode. Single-threaded
parallelStream() Sets up a flow that handles items by utilising threads for simultaneous execution. Multi-threaded

 

Write a Java 8 program to find the common elements between two lists using Stream API.

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class CommonElements { public static void main(String[] args) { List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> list2 = Arrays.asList(4, 5, 6, 7, 8); // Find common elements using Stream API List<Integer> commonElements = list1.stream() .filter(list2::contains) .collect(Collectors.toList()); // Print the common elements System.out.println(commonElements); } }

What is MetaSpace? How does it differ from PermGen?

Feature MetaSpace (Java 8) PermGen (Java 7 and earlier)
Memory Allocation Allocated in native memory, grows dynamically. Allocated in heap memory, fixed size by default.
Garbage Collection Automatically managed, no need to specify size. Can cause OutOfMemoryError if exceeded.
Configuration Size can be controlled with MaxMetaspaceSize flag. Configured using PermSize and MaxPermSize.

 

Can a Functional Interface extend or inherit another interface?

Yes, a Functional Interface can extend another interface, provided that the extended interface does not have more than one abstract method. If it inherits multiple default methods, there should not be any ambiguity between them.

Write a Java 8 program to implement a custom Functional Interface that multiplies two numbers.

@FunctionalInterface interface Multiply { int apply(int a, int b); } public class CustomFunctionalInterface { public static void main(String[] args) { // Implement the Functional Interface using Lambda Expression Multiply multiply = (a, b) -> a * b; // Use the custom Functional Interface int result = multiply.apply(5, 4); System.out.println("Multiplication result: " + result); } }

What is the difference between map and reduce in Stream?

Method Description Output
map() Transforms each element in the stream to another form using a given function. Stream of transformed elements
reduce() Combines the elements of a stream into a single result using an associative function. Single value (e.g., sum)

What are the advantages of using the Optional class?

  • Prevents NullPointerException by providing a container for nullable objects.
  • Provides methods like isPresent(), orElse(), orElseGet(), and ifPresent() for safe access.
  • Encourages better coding practices by handling optional values explicitly.

How are Collections different from Stream?

Feature Collections Stream
Storage Stores data (e.g., List, Set, Map). Does not store data; processes data pipeline.
Mutability Can be modified (add, remove elements). Immutable; cannot modify original source.
Computation Eager; performs computations immediately. Lazy; computations are deferred until terminal operation.
Traversal Can be traversed multiple times. Can be traversed only once.

 

Write a Java 8 program to find the average length of strings in a list.

import java.util.Arrays; import java.util.List; public class AverageStringLength { public static void main(String[] args) { List<String> words = Arrays.asList("Java", "Stream", "API"); // Calculate the average length of strings using Stream API double averageLength = words.stream() .mapToInt(String::length) .average() .orElse(0); // Print the average length System.out.println("Average length: " + averageLength); } }

What are the sources of data objects a Stream can process?

  • Collections: List, Set, Map, etc.
  • Arrays: Arrays of any type (int[], String[], etc.).
  • I/O Channels: Files, network sockets.
  • Generating Functions: Infinite streams generated by methods like Stream.generate().

What is the difference between Stream and iteration?

Feature Stream Iteration
Execution Uses internal iteration (automatic parallelism). Uses external iteration (manual control).
Functional Style Supports functional programming with declarative code. Requires imperative code with explicit loops.
Laziness Lazily evaluated; computations are deferred. Eager evaluation; computations are done immediately.

Java 8 Interview Questions for Experienced

What is a Type Interface?

In the Java programming language, a Type Interface is a feature that enables the compiler to figure out the type of a variable or expression by looking at its context. This comes in handy when working with Lambda Expressions and method references as it allows developers to write code that’s clearer and shorter due to the types being derived from the surrounding context.

What are the differences between Collectors.toList(), Collectors.toSet(), and Collectors.toMap() in Java 8?

 

Collector Method Description Output Type Duplicates Allowed
Collectors.toList() Collects the stream elements into a List. List<T> Yes
Collectors.toSet() Collects the stream elements into a Set, eliminating duplicates. Set<T> No
Collectors.toMap() Collects the stream elements into a Map using a key-value mapper function. Map<K, V> No (keys must be unique)

 

What does the String::valueOf expression mean?

The expression String::valueOf refers to the valueOf method, within the String class and is utilised for converting data types (integers or characters) into a string format. For example, String::valueOf can be used in streams to map elements to their string form.

How do BiConsumer, BiFunction, and BiPredicate interfaces differ in Java 8?

Interface Description Method Signature
BiConsumer Represents an operation that accepts two input arguments and returns no result. void accept(T t, U u)
BiFunction Represents a function that accepts two arguments and produces a result. R apply(T t, U u)
BiPredicate Represents a predicate (boolean-valued function) of two arguments. boolean test(T t, U u)

 

What is the purpose of the java.util.concurrent.ConcurrentHashMap class in Java 8?

ConcurrentHashMap is, like a version of HashMap that was added to the package, in Java programming language enabling multiple threads to access it simultaneously without requiring explicit synchronisation. The map is divided into segments, reducing contention and increasing performance, making it ideal for scenarios requiring high-concurrency read and write operations.

Can Lambda Expressions access variables outside their scope?

Lambda Expressions have the ability to reach outside their boundaries and interact with variables, like ones defined in the surrounding method or fields of the class. Nonetheless, it’s crucial that these local variables remain effectively final by not allowing their values to be altered after assignment.

How do Lambda Expressions differ from anonymous classes in Java?

Feature Lambda Expressions Anonymous Classes
Syntax More concise and readable. More verbose; requires class declaration.
Usage Can be used with functional interfaces only. Can implement multiple methods/interfaces.
this Reference Refers to the enclosing class instance. Refers to the instance of the anonymous class itself.
Performance More efficient, less overhead. Slightly more overhead due to class creation.

 

Write a Java 8 program to retrieve the names of all employees from a collection of employee objects.

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; class Employee { private String name; private int age; Employee(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } } public class EmployeeNames { public static void main(String[] args) { List<Employee> employees = Arrays.asList( new Employee("Alice", 30), new Employee("Bob", 25), new Employee("Charlie", 35) ); // Retrieve the names of all employees using Stream API List<String> employeeNames = employees.stream() .map(Employee::getName) .collect(Collectors.toList()); // Print the list of names System.out.println(employeeNames); } }

What are the differences between Comparable and Comparator in Java?

Feature Comparable Comparator
Purpose Used to define natural ordering of objects. Used to define custom ordering of objects.
Method compareTo(Object o) compare(Object o1, Object o2)
Interface Implemented by the class whose instances are compared. Implemented separately from the class being compared.
Usage Single default sorting sequence. Multiple custom sorting sequences can be defined.

How is a Functional Interface created in Java 8 in detail?

When we make a Functional Interface, in programming languages, like Java or Kotlin, we define an interface that has one method known as the Single Abstract Method (SAM). This interface can include default or static methods. Example:

@FunctionalInterface interface Calculator { int calculate(int a, int b); // Single abstract method (SAM)   default void display() { System.out.println("This is a calculator."); }   static void info() { System.out.println("Functional Interface Example."); } }

What is the most common type of Terminal Operations?

Type of Terminal Operations Description Example Methods
Reduction Operations Combines elements of a stream to produce a single result. reduce(), collect(), count()
Iterative Operations Performs an action for each element in the stream. forEach(), forEachOrdered()
Match Operations Checks whether elements match a given predicate. anyMatch(), allMatch(), noneMatch()
Optional Return Operations Retrieves elements from the stream, may return an Optional. findFirst(), findAny()

Write a Java 8 program to filter out strings that start with the letter ‘A’ from a list of strings.

Example:

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class FilterStrings { public static void main(String[] args) { List<String> words = Arrays.asList("Apple", "Banana", "Avocado", "Cherry", "Apricot"); // Filter out strings that start with the letter 'A' List<String> filteredWords = words.stream() .filter(word -> !word.startsWith("A")) .collect(Collectors.toList()); // Print the filtered list System.out.println(filteredWords); } }

When to use map and flatMap?

Method Purpose Use Case
map() Transforms each element in a stream to another form. Use when a one-to-one mapping is required.
flatMap() Flattens nested structures and transforms each element. Use when a one-to-many mapping is needed, or when dealing with nested streams.

What is the difference between stream and foreach in Java 8?

Feature stream() forEach()
Type Provides a sequence of elements to perform functional operations on. Performs an action for each element of the collection.
Use Case Use for transforming, filtering, or reducing data. Use for iterating and performing actions.
Returns A new Stream object with modified data. void; does not return a modified collection.

Explain the skip(long) using an example.

The skip(long n) method in Java 8 is an intermediate operation that discards the first n elements of a stream. This technique comes in handy in situations when you need to disregard a quantity.

Example:

import java.util.stream.Stream; public class SkipExample { public static void main(String[] args) { // Create a stream and skip the first 3 elements Stream.of("one", "two", "three", "four", "five") .skip(3) .forEach(System.out::println); // Output: four, five } }

What is the difference between Iterator and Spliterator?

Feature Iterator Spliterator
Traversal Supports only sequential traversal. Supports both sequential and parallel traversal.
Characteristics No special characteristics. Has characteristics like ORDERED, SORTED, DISTINCT, NONNULL, etc.
Splitting Capability Cannot split. Can split itself to support parallel processing.
Methods hasNext(), next(), remove(). tryAdvance(), trySplit(), characteristics().

 

Write a Java 8 program to find a Stream’s minimum and maximum number.

import java.util.Arrays; import java.util.List; import java.util.Optional;   public class MinMaxExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(3, 5, 7, 2, 8);   // Find the minimum number using Stream API Optional<Integer> min = numbers.stream().min(Integer::compareTo);   // Find the maximum number using Stream API Optional<Integer> max = numbers.stream().max(Integer::compareTo);   // Print the results min.ifPresent(value -> System.out.println("Minimum number: " + value)); max.ifPresent(value -> System.out.println("Maximum number: " + value)); } }

Can you use ‘this’ keyword inside a Lambda Expression?

In Lambda Expressions, ‘this’ points to the enclosing class instance and not the lambda itself as it does in classes where ‘this’ points to the class instance. However in lambdas, ‘this’ refers to the enclosing class instance.

What are the different types of references supported by Java 8’s Garbage Collector?

  • Strong Reference: Default type of reference. It prevents objects from being collected by the Garbage Collector.
  • Weak Reference: The object is eligible for garbage collection if no strong references exist.
  • Soft Reference: Used for memory-sensitive caches; collected only if the JVM is low on memory.
  • Phantom Reference: Used to perform cleanup actions before an object is removed from memory.

What is the purpose of IntStream and LongStream interfaces in Java 8?

The IntStream and LongStream interfaces are specialised streams for working with primitive data types int and long, respectively. They provide methods like sum(), average(), max(), and min() optimised for handling large collections of numeric data efficiently. These interfaces assist in minimising the work involved in converting between data types while using Stream<Integer> or Stream<Long>.

How would you find the sum of all even numbers in a list?

To calculate the total of all numbers in a list, with Java 8 programming language you can apply the filter() function to isolate the numbers and then utilise either the reduce() function or sum() function to determine the sum.

import java.util.Arrays; import java.util.List; public class SumEvenNumbers { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);   // Find the sum of all even numbers int sum = numbers.stream() .filter(n -> n % 2 == 0) // Filter even numbers .mapToInt(Integer::intValue) .sum(); // Sum the even numbers   // Print the sum System.out.println("Sum of even numbers: " + sum); } }

Is Stream API eager or lazy?

The Stream API in Java 8 is lazy. This means intermediate operations (like map(), filter()) are not executed until a terminal operation (like collect(), forEach(), reduce()) is invoked. This laziness allows optimization such as short-circuiting and reduced processing.

What are the main components of a Stream?

Component Description
Source The data source (like collections, arrays) that provides elements for the stream.
Intermediate Operations Operations (like filter(), map(), sorted()) that transform a stream into another stream.
Terminal Operations Operations (like collect(), forEach(), reduce()) that produce a result or side effect.

What is the difference between Collectors.toMap() and groupingBy() methods in Java 8?

Method Purpose Use Case
Collectors.toMap() Collects elements into a Map using a key and value mapping function. Used when you need a simple key-value mapping.
Collectors.groupingBy() Groups elements by a classifier function and returns a Map with keys as the classifier and values as lists of items. Used when you need to group elements into a Map of lists.

What is the difference between findFirst() and findAny() in parallel streams?

Method Description Use Case
findFirst() Returns the first element in the stream. Used when the order of elements matters.
findAny() Returns any element from the stream (more efficient in parallel streams). Used for parallel processing where order does not matter.

How would you demonstrate the difference between Predicate and Function using examples?

import java.util.function.Function; import java.util.function.Predicate;   public class PredicateFunctionExample { public static void main(String[] args) { // Example of Predicate: Checks if a number is greater than 10 Predicate<Integer> isGreaterThanTen = num -> num > 10; System.out.println("Is 15 greater than 10? " + isGreaterThanTen.test(15)); // Output: true   // Example of Function: Converts a number to its square Function<Integer, Integer> squareFunction = num -> num * num; System.out.println("Square of 5: " + squareFunction.apply(5)); // Output: 25 } }

Explain the behaviour of the collect() method with different types of Collectors.

Collector Type Description Example
Collectors.toList() Collects stream elements into a List. List<String> list = stream.collect(Collectors.toList());
Collectors.toSet() Collects stream elements into a Set (removes duplicates). Set<String> set = stream.collect(Collectors.toSet());
Collectors.toMap() Collects elements into a Map using key-value mapping functions. Map<Integer, String> map = stream.collect(Collectors.toMap(String::length, Function.identity()));
Collectors.groupingBy() Groups elements by a classifier function and returns a Map of lists. Map<String, List<String>> grouped = stream.collect(Collectors.groupingBy(String::toLowerCase));
Collectors.partitioningBy() Partitions elements into two groups based on a predicate and returns a Map<Boolean, List<T>>. Map<Boolean, List<String>> partitioned = stream.collect(Collectors.partitioningBy(s -> s.length() > 3));

Write a Java 8 program that uses a combination of map and flatMap to process nested lists.

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;   public class NestedListProcessing { public static void main(String[] args) { List<List<String>> nestedList = Arrays.asList( Arrays.asList("Java", "Python"), Arrays.asList("JavaScript", "C++"), Arrays.asList("Go", "Swift") );   // Use flatMap to flatten the nested lists and map to convert to uppercase List<String> processedList = nestedList.stream() .flatMap(List::stream) // Flatten the nested lists .map(String::toUpperCase) // Convert each element to uppercase .collect(Collectors.toList());   // Print the processed list System.out.println(processedList); } }

Conclusion

In conclusion, getting ready for a Java 8 interview involves grasping the more complex elements introduced in this release version of the programming language.Java 8 brings a variety of features like Lambda Expressions and Stream API along with interfaces and updated data types that are vital for today’s Java developers. Understanding these functionalities will demonstrate your proficiency and preparedness, for any position.

 

This blog discusses a range of interview queries, for newcomers and seasoned individuals alike. With a grasp of these subjects, you can adeptly handle Java 8 interview questions. Emerge as a standout contender, in any technical interview setting.

Upskill with expert articles

View all
Free courses curated for you
Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
Beginner level
icon
9 Modules
icon
Certification included
avatar
1800+ Learners
View
Essentials of Excel
Essentials of Excel
icon
4 Hrs. duration
icon
Beginner level
icon
12 Modules
icon
Certification included
avatar
2200+ Learners
View
Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
Beginner level
icon
12 Modules
icon
Certification included
avatar
2600+ Learners
View
next_arrow
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved