Sitemap
Omkar Bhavare

Omkar Bhavare

Articulating the 'why' behind the code. I dissect JS quirks, React's render cycle, Java fundamentals & DSA patterns to reveal the elegant systems beneath.

Java 8

16 min read5 days ago

--

What are Lambda Expressions in Java, and why were they introduced?

Lambda Expressions are a concise way to implement the single abstract method of a Functional Interface without creating a separate class or anonymous inner class. They were introduced in Java 8 to reduce boilerplate code and support functional programming. They allow us to pass behaviour as an argument and are commonly used with Collections, Streams, Comparators and event handling.

How do Lambda Expressions reduce boilerplate code?

Lambda expressions reduce boilerplate code by eliminating the need to create anonymous inner classes just to implement a Functional Interface. Instead of writing a separate method implementation with class syntax, we directly provide the behaviour using a simple expression.

For example, Runnable r = () -> System.out.println("Hello"); replaces the longer anonymous class implementation. This makes code shorter, cleaner and easier to maintain.

Can Lambda Expressions replace every anonymous inner class?

No, Lambda Expressions cannot replace every anonymous inner class. They can replace anonymous classes only when they implement a Functional Interface, which has exactly one abstract method.

Anonymous inner classes are still required when we need to extend an abstract or concrete class, implement multiple abstract methods, or maintain their own instance state. Also, this behaves differently: in a lambda, it refers to the enclosing object, whereas in an anonymous class, it refers to the anonymous class instance.

Press enter or click to view image in full size
Press enter or click to view image in full size

How are Lambda Expressions implemented at runtime?

In Java, lambda expressions are implemented using the invokedynamic mechanism. During compilation, the compiler generally creates a synthetic method containing the lambda logic and generates an invokedynamic instruction instead of creating a separate class file like an anonymous inner class.

At runtime, invokedynamic uses LambdaMetafactory to connect that implementation method with the target Functional Interface. The JVM then provides a suitable lambda object, and when we invoke the interface method, it executes the actual lambda logic. So basically, lambda uses dynamic linkage rather than the traditional anonymous class approach.

Press enter or click to view image in full size

How does Java determine the target type of a Lambda Expression?

Java determines the target type of a Lambda Expression from its surrounding context, such as a variable assignment, method argument, or type cast. The target type must be a Functional Interface, and its single abstract method defines the lambda’s parameter types and return type.

The compiler uses this information to understand which method the lambda is implementing and performs type checking accordingly. This is called Target Type Inference.

Press enter or click to view image in full size

How does the compiler conclude Lambda parameter types?

The compiler conclude Lambda parameter types from the target Functional Interface’s abstract method signature. It checks the method’s parameter types and assigns those types to the lambda parameters automatically, so we don’t need to declare them explicitly.

For example, if the functional method accepts a String, the lambda parameter is automatically treated as String. We can also specify parameter types explicitly when needed.

Press enter or click to view image in full size

Why can a Lambda be assigned to Runnable but not directly to Object?

A Lambda Expression can be assigned to Runnable because Runnable is a Functional Interface with exactly one abstract method, run(). The compiler uses this method's signature to understand what the lambda should implement.

Object is not a Functional Interface because it does not define a single abstract method contract. A lambda needs a functional interface as its target type, so it cannot be assigned directly to Object. We can first assign it to Runnable and then store that Runnable object in an Object reference.

How does the this keyword behave inside a Lambda Expression?

Inside a Lambda Expression, this refers to the current instance of the enclosing class, not the Lambda Expression itself. This is because lambdas do not create their own this context; they use the surrounding class's context. The main benefit is that a Lambda Expression can directly access the enclosing class’s instance methods and variables without confusion about this. It also makes code simpler because a lambda doesn’t create a separate object context for this. This is particularly useful when working with callbacks, event handling, and functional interfaces, where we want to access the current class's state or methods.

In contrast, inside an anonymous inner class, this refers to the anonymous class instance.

Press enter or click to view image in full size

What are effectively final variables in Lambda Expressions?

Effectively final variables are local variables whose values are assigned only once and are not reassigned afterwards, even if we haven’t explicitly declared them using the final keyword.

Lambda Expressions can access local variables only if they are final or effectively final. Java doesn't automatically make a variable final; it simply checks whether we have reassigned it. If we reassign it, the lambda cannot capture that variable.

However, if the variable references a mutable object, we can still modify that object’s internal state without reassigning the reference.

Press enter or click to view image in full size

What is a Functional Interface, and what makes it a SAM interface?

A Functional Interface is an interface that contains exactly one abstract method. It is also called a SAM (Single Abstract Method) interface because it defines a single abstract method that a Lambda Expression can implement.

It can still contain multiple default and static methods because they are not abstract methods. We can use the @FunctionalInterface annotation to let the compiler validate that the interface follows this contract. Common examples are Runnable, Comparator, Predicate and Function.

Why can a Functional Interface have only one abstract method?

A Functional Interface has only one abstract method so that a Lambda Expression has one unambiguous method contract to implement. When we write a lambda, the compiler knows exactly which method the lambda body represents.

If multiple unrelated abstract methods were allowed, the compiler wouldn’t know how to map a single lambda expression to those methods. This single-method contract is what makes lambda expressions simple and predictable.

Can a Functional Interface extend another interface?

Yes, a Functional Interface can extend another interface, provided the resulting interface still has exactly one abstract method.

For example, if the parent interface has one abstract method and the child doesn’t introduce another abstract method, it remains a Functional Interface. We can also extend multiple interfaces if their abstract methods have compatible signatures and represent the same method contract.

Can an interface be functional without @FunctionalInterface?

Yes, an interface can be a Functional Interface without the @FunctionalInterface annotation, as long as it contains exactly one abstract method. The annotation is optional; it simply tells the compiler to validate the Functional Interface contract and report an error if the interface violates it.

What happens when two inherited abstract methods have the same signature?

When two inherited abstract methods have the same signature and compatible return types, Java treats them as a single abstract method, not two separate methods. This means the child interface can still qualify as a Functional Interface and be implemented using a Lambda Expression.

However, if their return types are incompatible, the compiler reports an error. For example, two parent interfaces declaring void execute() can be extended by one functional child interface.

Can overloaded methods accepting different Functional Interfaces create ambiguity?

Yes, overloaded methods accepting different Functional Interfaces can create ambiguity when the same Lambda Expression is compatible with both interfaces.

For example, if two methods accept Predicate<String> and Function<String, Boolean>, a lambda like s -> s.isEmpty() can match both because their abstract methods have compatible parameter and return types. The compiler cannot decide which overloaded method to call.

We can resolve this using an explicit type cast or by assigning the lambda to a specifically typed Functional Interface variable before passing it.

What are the commonly used Functional Interfaces in Java?

Press enter or click to view image in full size

What are Predicate, Function, Consumer and Supplier?

Get Omkar Bhavare’s stories in your inbox

Join Medium for free to get updates from this writer.

Predicate

“Predicate takes one input and returns a boolean. Its method is test(). I use it for conditions, like filtering or validation.”

import java.util.function.Predicate;

Predicate<Integer> isAdult = age -> age >= 18;

System.out.println(isAdult.test(20)); // true
System.out.println(isAdult.test(15)); // false

Predicate<String> validPassword = pwd -> pwd.length() >= 8;
System.out.println(validPassword.test("abc12345")); // true

Function

“Function takes one input and returns one output. The output can be a different type. Its method is apply(). I use it to transform data from one form to another.”

import java.util.function.Function;

Function<String, Integer> length = text -> text.length();

System.out.println(length.apply("Hello")); // 5

Consumer

“Consumer takes one input and returns nothing. Its method is accept(). I use it when I want to perform an action, like printing, logging or saving. It usually has a side effect”

import java.util.function.Consumer;

Consumer<String> printer = message -> System.out.println(message);

printer.accept("Hello"); // prints Hello

Supplier

“Supplier takes no input and returns a value. Its method is get(). I use it when I want to create or provide a value only when it is needed. This is called lazy evaluation.”

import java.util.function.Supplier;

Supplier<Double> randomNumber = () -> Math.random();

System.out.println(randomNumber.get()); // a new value each call

Generating data such as IDs:

Supplier<String> idGenerator = () -> UUID.randomUUID().toString();
System.out.println(idGenerator.get());

When should we create a custom Functional Interface?

We create a custom Functional Interface when the predefined interfaces like Predicate, Function, Consumer and Supplier don't clearly represent our business requirement.

For example, if we need a reusable operation like calculateDiscount(double amount), we can define our own interface with that method. Custom interfaces are also useful when we need domain-specific naming, custom input/output types, or checked exception handling.

Use built-in Functional Interfaces wherever possible; create custom ones only when they improve clarity or meet a specific requirement.

What is Stream API, and how is it different from a Collection?

Stream API is a feature introduced in Java 8 that helps us process data from collections using operations like filtering, sorting, mapping and counting, without writing repetitive loops.

A Collection stores data, while a Stream is used to process that data. Stream operations are lazy, meaning processing starts when a terminal operation is called, and a Stream can be used only once.

Can a Stream modify its source collection?

A Stream does not modify its source collection by default. Operations like filter(), map() and sorted() process the data and produce results without changing the original collection.

However, if we explicitly modify objects inside the Stream or perform external side effects, the underlying data can change. So, Stream operations are generally expected to be stateless and non-interfering.

Can the same Collection create multiple Streams?

Yes, the same Collection can create multiple Streams because a Collection can be traversed multiple times.

However, a Stream can beconsumed only once. We can create a new Stream from the same Collection whenever we need another processing operation.

How does Stream API work internally?

Stream API internally processes data through a pipeline of operations. It starts with a source, such as a Collection, followed by intermediate operations like filter() or map(), and finally a terminal operation like collect() or forEach().

Intermediate operations are lazy, so actual processing starts only when the terminal operation is called. Internally, Stream processes elements through this pipeline rather than creating a new collection after every operation.

How is a Stream pipeline created and executed in Java, and what is the role of intermediate and terminal operations? Are both mandatory to execute a Stream? What happens if either is missing?

A Stream pipeline is created in three stages:

1. Source: Data comes from a Collection, array or another data source.

2. Intermediate operations: Operations like filter(), map() and sorted() transform or filter the data. They are lazy, meaning they don't process data immediately. We can have zero or multiple intermediate operations.

3. Terminal operation: Operations like collect(), forEach() or count() trigger the actual processing and produce a result or perform an action.

Are both intermediate and terminal operations mandatory?

No. Intermediate operations are optional, but a terminal operation is required to execute the Stream pipeline.

Without intermediate operations: The Stream can directly execute a terminal operation on the source data.

Without a terminal operation: The pipeline is not executed. Intermediate operations remain pending because they are lazy.

Key interview point: A Stream pipeline can have zero or more intermediate operations, but only one terminal operation.

What is the difference between intermediate and terminal operations?

Intermediate operations are used to filter, transform or sort Stream elements. They return another Stream and are lazy, meaning they execute only when a terminal operation is called.

Examples: filter(), map(), sorted().

Terminal operations trigger the execution of the Stream pipeline and produce a final result or perform an action.

Examples: collect(), forEach(), count().

Key difference: Intermediate operations build the processing pipeline, while terminal operations trigger and complete its execution.

List<Integer> numbers = List.of(10, 15, 20, 25);

List<Integer> result = numbers.stream()
.filter(n -> n > 15) // Intermediate
.map(n -> n * 2) // Intermediate
.collect(Collectors.toList()); // Terminal

Why are intermediate operations lazy?

In Java Streams, intermediate operations like filter(), map() and sorted() are lazy, meaning they don't process elements immediately when we add them to the pipeline. Instead, Java builds and records the processing pipeline, and the actual processing begins only when a terminal operation like collect(), forEach() or count() is invoked.

Lazy evaluation helps avoid unnecessary processing because Java can process elements on demand, skip elements, or stop early when the result is achieved, such as with findFirst() or anyMatch(). This makes Stream processing more efficient in many scenarios.

What happens if we create a Stream pipeline without a terminal operation?

The Stream pipeline is created, but it is not executed because intermediate operations are lazy. Java doesn’t process the elements until a terminal operation is invoked.

As a result, intermediate operations like filter() or map() won't actually run, and their processing logic won't be executed.

Press enter or click to view image in full size

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

map() transforms each element into another element, maintaining one output per input element. flatMap() transforms each element into a Stream or collection of elements and then flattens them into a single Stream.

  • map() – One-to-one transformation.
  • flatMap() – One-to-many transformation followed by flattening.

We use map() for simple transformations and flatMap() when nested data needs to be converted into a single flat sequence.

How does map() transform each element?

map() takes each element from the Stream, applies a transformation function, and returns the transformed element in a new Stream. It doesn't change the original data by default.

For example, we can use map() to convert employee objects into employee names, or convert numbers into their squares. Each input element produces one output element.

What happens when map() returns a Stream?

When map() returns a Stream for each element, the result becomes a Stream of Streams, meaning the nested structure remains. map() does not automatically flatten those inner Streams.

If we want to combine the elements of those inner Streams into one Stream, we use flatMap() instead.

How does flatMap() flatten nested collections

flatMap() takes each element, converts it into a Stream of elements, and then combines all those individual Streams into one single Stream. It removes the nested structure during Stream processing.

For example, when we have a List of Lists, flatMap() can combine their elements into one Stream, which makes filtering, searching or collecting across all elements easier.

Why does flatMap() avoid nested Stream structures?

flatMap() is designed to map each input element to a Stream and then flatten all those Streams into a single Stream. This flattening is part of its operation, so the nested Stream structure doesn't remain.

This is useful when each input element can produce multiple elements, and we want to process all of them in one continuous pipeline.

Press enter or click to view image in full size

What is Spliterator & explain its role ?

Spliterator (Splitable Iterator) is an interface introduced in Java 8 to traverse and split elements of a data source. Unlike Iterator, it can divide data into smaller parts, which helps Stream API perform parallel processing efficiently.

Its main role is to traverse elements using tryAdvance() and split data using trySplit(). It also provides information about the data, such as whether it is ordered, sized or distinct, which helps Streams optimize processing.

Press enter or click to view image in full size

What are stateless and stateful Stream operations?

Stateless operations process each element independently, without needing information from previously processed elements. They are generally easier to execute efficiently and in parallel. Examples: filter() and map().

Stateful operations need to maintain or consider information about other elements before processing or producing results. Examples: sorted() and distinct().

The key difference is that stateless operations process elements independently, while stateful operations may need to retain or examine data across elements, potentially requiring more memory or processing.

What is short-circuiting in Stream API?

Short-circuiting in Stream API means processing can stop early when an operation has enough information to determine the final result, without processing all elements.

Operations like findFirst(), findAny(), anyMatch(), allMatch() and noneMatch() can short-circuit. Some intermediate operations like limit() also restrict how many elements need to be processed, but a terminal operation is still required to trigger execution.

What is reduce() in Stream API, and how does it work?

reduce() is a terminal operation used to combine Stream elements into a single result by repeatedly applying an operation. It is commonly used for aggregation, such as calculating sum, product or finding a combined value.

It takes elements and combines them step by step using an accumulator function. Depending on the overload, it can also accept an initial value, which makes the result more predictable and avoids an empty Stream issue.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);

System.out.println(sum); // 15

List<String> words = Arrays.asList("Java", "Stream", "API");

int totalLength = words.stream()
.reduce(0,
(total, word) -> total + word.length(),
Integer::sum);

System.out.println(totalLength); // 13
Press enter or click to view image in full size

What Is parallel execution ?

Parallel execution means processing multiple parts of a task simultaneously using multiple threads, instead of processing everything sequentially on a single thread.

In Java Streams, parallelStream() divides the data into smaller parts, processes those parts concurrently, and combines the results when required. It can improve performance for suitable workloads, but thread overhead, data size and operation complexity determine whether it actually helps.

What is parallel stream ? How does Parallel Stream processing work internally?

Parallel Stream is a feature of Java Stream API that allows data to be processed concurrently by dividing it into smaller parts and processing those parts using multiple threads.

Internally, it uses Spliterator to split the data, typically uses the ForkJoinPool common pool to execute tasks across threads, and combines partial results when needed. This can improve performance for large, CPU-intensive workloads, but parallel processing is not always faster because splitting, coordination and combining also have overhead.

What is stream ? How does parallelStream() differ from stream()?

A Stream is a sequence of data elements that allows us to process data using operations like filtering, mapping and sorting, without storing the data itself.

  • stream() processes elements sequentially, typically on a single thread.
  • parallelStream() divides the data into smaller parts and processes them concurrently using multiple threads, typically through the ForkJoinPool common pool.

Parallel Streams can improve performance for large, CPU-intensive tasks, but they may add overhead and are not always faster.

Is Stream pipeline thread-safe? What makes a Stream pipeline thread-safe during parallel execution?

A Stream pipeline is not automatically thread-safe. In parallel execution, multiple threads may process different elements simultaneously, so thread safety depends on how the operations are written.

We should avoid shared mutable state, keep operations stateless and non-interfering, and avoid modifying the source while processing. Java’s built-in reduction operations like collect() are designed to combine partial results safely when used correctly.

Key point: Parallel Streams handle task splitting and combining, but they don’t automatically make our code or shared objects thread-safe.

How can we make Stream pipeline threadsafe ?

We make a Stream pipeline safe for parallel execution by avoiding shared mutable state and keeping operations stateless. Each element should be processed independently wherever possible.

Use built-in reduction operations like collect(), reduce() and suitable collectors instead of modifying shared variables. Also, avoid modifying the source collection during processing and use thread-safe structures when shared state is genuinely required.

Key point: We don’t make the Stream itself thread-safe; we write the operations so concurrent execution doesn’t cause race conditions.

What is Optional in Java, and what problem does it solve?

Optional is a container introduced in Java 8 that may contain a value or may be empty. It helps handle situations where a value might be absent, reducing the chances of NullPointerException.

Instead of directly returning null, a method can return Optional to explicitly indicate that a value may or may not be available. It provides methods like isPresent(), orElse(), orElseGet() and ifPresent() to handle missing values safely.

Does Optional eliminate NullPointerException completely?

No, Optional does not eliminate NullPointerException completely. It helps handle potentially missing values explicitly, but we can still get an NPE if the Optional itself is null, if we call get() on an empty Optional, or if other objects in our code are null.

Optional reduces the chances of null-related errors when used correctly; it is not a replacement for proper null handling everywhere.

What is eager evaluation & lazy evaluation? When to use when

Eager evaluation means an expression is evaluated immediately when it is encountered, even if its result might not be needed.

Lazy evaluation means an expression is evaluated only when its result is actually required.

When to use which?

Eager evaluation: Use it when the operation is simple, inexpensive and always needed.

Lazy evaluation: Use it when the operation is expensive or should execute only when required.

Example:

  • Streams: Intermediate operations are lazy. They execute only when a terminal operation is called.
  • Optional: orElse() evaluates its fallback value eagerly, whereas orElseGet() evaluates the fallback Supplier only when Optional is empty.

Interview point: Lazy evaluation helps avoid unnecessary computation and can improve performance, especially when operations are expensive.

What is Future & CompletableFuture, and explain how are they different?

Future represents the result of an asynchronous task that may be available later. We can check whether the task is completed or wait for its result using get(), but it has limited support for chaining or combining tasks.

CompletableFuture, introduced in Java 8, extends this capability by allowing us to chain tasks, combine multiple asynchronous operations, handle exceptions and continue processing without blocking unnecessarily.

  • Future: We submit a task and wait for its result when needed.
  • CompletableFuture: We can build an asynchronous workflow where one task triggers another, multiple tasks run together, and exceptions are handled within the pipeline.

Practical example: In an application, we might fetch user details and order details from separate services simultaneously using CompletableFuture, then combine both responses. With a basic Future, we typically need to wait for and manually combine the results, making asynchronous workflows harder to manage.

What is method reference?

Method reference is a shorthand notation for a lambda expression. We use it when a lambda expression simply invokes an existing method, making the code cleaner and more readable

There are 4 types of method references:

1. Static method reference — ClassName::staticMethod

2. Instance method reference — object::instanceMethod

3. Instance method reference of an arbitrary object --ClassName::instanceMethod

4. Constructor reference — ClassName::new

--

--

Omkar Bhavare
Omkar Bhavare

Written by Omkar Bhavare

Articulating the 'why' behind the code. I dissect JS quirks, React's render cycle, Java fundamentals & DSA patterns to reveal the elegant systems beneath.