Java 8 interview questions and answers: lambdas, streams and more
Java 8 interview questions focus on the release that brought functional programming into everyday Java: lambdas and functional interfaces, method references, the Stream API and its collectors, Optional, default methods on interfaces, the java.time date API and CompletableFuture. Interviewers expect you to write a stream pipeline from memory, explain why it is lazy, and say when a plain loop is the better choice. Many codebases still run on Java 8 or were written in its style, so these questions remain common for experienced developers too.
By Evin JohnPublished 10 min read
How Java 8 questions come up
Job posts that say "Java 8" usually mean a backend or full-stack Java role where the codebase uses streams, lambdas and the newer date API everywhere. The Java 8 block of the interview tends to sit between core Java and framework questions. Freshers get definitions and a short stream to write. Experienced candidates get a refactor (turn this loop into a stream, or the reverse), a concurrency question with CompletableFuture, or a bug caused by a lazy pipeline. Broader topics such as collections internals, the JVM and Spring are covered in Java developer interview questions.
- Concept checksFunctional interfaces, lambda rules, method reference kinds, default methods.
- Write a pipelineGroup, count, sort or join data with streams and collectors, usually in a shared editor.
- Explain behaviorWhy nothing printed, why a parallel stream was slower, why a date was off by an hour.
Lambdas and functional interfaces
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is a functional interface? | Core idea | An interface with exactly one abstract method, such as Runnable or Comparator. Default and static methods do not count. @FunctionalInterface makes the compiler enforce the rule. |
| Name the main types in java.util.function. | Standard library | Function (T to R), Consumer (takes T, returns nothing), Supplier (returns T), Predicate (T to boolean), BiFunction, UnaryOperator and BinaryOperator, plus primitive versions such as IntPredicate that avoid boxing. |
| What does effectively final mean for lambdas? | Capture rules | A lambda may read local variables only if they are never reassigned. It captures the value, not the variable, so mutation would be ambiguous. Fields and array contents are not covered by this rule, which is a common source of thread-safety bugs. |
| How is this different inside a lambda and an anonymous class? | Scope | In a lambda, this is the enclosing instance. In an anonymous class, this is the anonymous object itself. Lambdas also cannot shadow local variable names from the enclosing scope. |
| What are the four kinds of method reference? | Syntax | Static (Integer::parseInt), bound instance (System.out::println), unbound instance of an arbitrary object (String::length) and constructor (ArrayList::new). |
| Can a lambda throw a checked exception? | Exceptions | Only if the functional interface's method declares it. The java.util.function types do not, so you wrap the call, use a custom interface, or handle the exception inside. |
| How do Function.andThen and compose differ? | Composition | f.andThen(g) runs f then g. f.compose(g) runs g then f. Predicate has and, or and negate for building conditions. |
| Is a lambda compiled to an anonymous inner class? | Implementation | No. The compiler emits an invokedynamic call site, and the runtime builds the implementation on first use, so there is no separate class file per lambda. |
| Why do primitive specializations such as IntStream exist? | Performance | Boxing every int into an Integer costs memory and time. IntStream, LongStream and DoubleStream work on primitives and add sum, average and summaryStatistics. |
Stream API questions
- What is the difference between intermediate and terminal operations? Intermediate ones such as filter, map and sorted return a new stream and do nothing yet. A terminal one such as collect, forEach, reduce or findFirst runs the pipeline and closes the stream.
- Why did my stream print nothing? It had no terminal operation, so the lambdas in peek or map never ran.
- Can a stream be reused? No. After a terminal operation it is consumed, and a second use throws IllegalStateException. Keep a Supplier of streams or the source collection instead.
- What is short-circuiting? Operations such as findFirst, anyMatch and limit stop pulling elements once they have an answer, which is why streams can work on infinite sources from Stream.iterate or Stream.generate.
- Which operations are stateful, and why does it matter? sorted and distinct must see many or all elements before passing any on. They hold memory and limit parallel speedups.
- reduce or collect? reduce combines immutable values, such as a sum. collect builds a mutable container such as a list or map, which is cheaper than creating a new collection at every step.
- What does toMap do with duplicate keys? The two-argument form throws IllegalStateException. Pass a merge function as the third argument, and a map supplier as the fourth if you need ordering.
- How do partitioningBy and groupingBy differ? partitioningBy splits into exactly two groups by a predicate, keyed true and false. groupingBy makes as many groups as there are distinct keys and accepts a downstream collector.
- When is a parallel stream slower? Small inputs, sources that split badly such as LinkedList, heavy boxing, ordered operations such as findFirst, and blocking I/O. All parallel streams share the common ForkJoinPool by default, so one slow task can starve others.
import java.time.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.*;
import java.util.stream.*;
public class Java8Demo {
static class Order {
final String city; final double total; final LocalDate placed;
Order(String city, double total, LocalDate placed) { this.city = city; this.total = total; this.placed = placed; }
String getCity() { return city; }
double getTotal() { return total; }
}
public static void main(String[] args) {
List<Order> orders = Arrays.asList(
new Order("Pune", 120.0, LocalDate.of(2026, 3, 1)),
new Order("Austin", 80.0, LocalDate.of(2026, 3, 2)),
new Order("Pune", 45.5, LocalDate.of(2026, 3, 9)));
// Revenue per city, sorted by key for stable output
Map<String, Double> byCity = orders.stream()
.collect(Collectors.groupingBy(Order::getCity, TreeMap::new,
Collectors.summingDouble(Order::getTotal)));
System.out.println(byCity); // {Austin=80.0, Pune=165.5}
// Laziness: peek only runs for elements pulled by findFirst
Optional<Order> firstBig = orders.stream()
.peek(o -> System.out.println("checking " + o.city))
.filter(o -> o.total > 100)
.findFirst();
System.out.println(firstBig.map(Order::getCity).orElse("none")); // checking Pune, then Pune
// Function composition
Function<Double, Double> withTax = t -> t * 1.1;
Function<Double, Long> rounded = withTax.andThen(Math::round);
System.out.println(rounded.apply(45.5)); // 50
// java.time is immutable: plusDays returns a new object
LocalDate placed = LocalDate.of(2026, 3, 9);
placed.plusDays(5);
System.out.println(placed + " " + placed.plusDays(5).getDayOfWeek()); // 2026-03-09 SATURDAY
// CompletableFuture: combine two async results
CompletableFuture<Integer> stock = CompletableFuture.supplyAsync(() -> 7);
CompletableFuture<Integer> reserved = CompletableFuture.supplyAsync(() -> 2);
System.out.println(stock.thenCombine(reserved, (s, r) -> s - r).join()); // 5
}
}Expect follow-ups on this file: why only one "checking" line printed, why the TreeMap supplier was passed, and why the bare placed.plusDays(5) call changed nothing.
Optional and default methods
- What problem does Optional solve, and what does it not solve? It makes "maybe no value" visible in a return type and offers map, flatMap, filter and orElse chains. It does not remove NullPointerException from the language, and it is not meant for fields, parameters or serialization.
- orElse versus orElseGet? orElse evaluates its argument every time, even when a value is present. orElseGet takes a Supplier and runs it only when empty, which matters if the fallback is expensive.
- Optional.of versus Optional.ofNullable? of throws immediately on null, which documents a programming error. ofNullable wraps a value that may legitimately be absent.
- Why were default methods added? To let interfaces such as Collection gain methods like stream and forEach without breaking every existing implementation.
- What happens when two interfaces provide the same default method? The class fails to compile until it overrides the method, and it can call a specific parent with InterfaceName.super.method(). A method from a superclass always wins over an interface default.
- Can interfaces have static methods now? Yes, since Java 8. They are called through the interface name and are not inherited by implementing classes, which is how Comparator.comparing and friends are offered.
public class Defaults {
interface Camera { default String describe() { return "camera"; } }
interface Phone { default String describe() { return "phone"; } }
// Both interfaces supply describe(), so the class must resolve the clash itself.
static class SmartPhone implements Camera, Phone {
@Override public String describe() {
return Phone.super.describe() + " with " + Camera.super.describe();
}
}
public static void main(String[] args) {
System.out.println(new SmartPhone().describe()); // phone with camera
}
}java.time questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Why was java.time introduced? | Motivation | Date and Calendar are mutable, not thread-safe, and confusing (months counted from zero in Calendar). java.time types are immutable, thread-safe and clearly named. |
| LocalDateTime, ZonedDateTime or Instant? | Choosing types | Instant is a point on the UTC timeline, good for storage and logs. ZonedDateTime adds a region such as Europe/Paris and handles daylight saving. LocalDateTime has no zone and suits things like "the store opens at 9:00". |
| Duration versus Period? | Amounts of time | Duration is machine time in seconds and nanoseconds. Period is calendar time in years, months and days, so adding one month respects month lengths. |
| How do you format and parse dates safely? | Formatting | DateTimeFormatter, which is immutable and thread-safe, unlike SimpleDateFormat, which must not be shared across threads. |
| What happens when you add a day across a daylight-saving change? | Edge cases | ZonedDateTime.plusDays keeps the local time where possible, while plus(Duration.ofHours(24)) adds exact elapsed time, so the results can differ by an hour. |
Concurrency and runtime changes in Java 8
- Future versus CompletableFuture? A Future can only be polled or blocked on. CompletableFuture can be chained with thenApply, thenCompose and thenCombine, completed manually, and recovered with exceptionally or handle.
- thenApply versus thenCompose? thenApply maps the result with a plain function. thenCompose takes a function that returns another CompletableFuture and flattens it, much like flatMap.
- Which executor runs supplyAsync by default, and why does it matter? The common ForkJoinPool. Blocking calls there can starve other async work and parallel streams, so pass your own executor for I/O.
- What did ConcurrentHashMap gain? Atomic compute, computeIfAbsent and merge, plus bulk operations such as forEach, search and reduce. merge is a tidy way to count words safely across threads.
- What is LongAdder for? A counter that spreads updates across cells under contention and sums them on read, faster than AtomicLong for hot counters that are read rarely.
- What replaced PermGen? Metaspace, which holds class metadata in native memory and grows as needed unless capped. Old PermGen sizing flags stopped having an effect.
- What changed inside HashMap? Buckets with many colliding keys turn into balanced trees once they pass a threshold, so worst-case lookups degrade far less than with long linked lists.
- Which smaller APIs arrived? String.join and StringJoiner, java.util.Base64, Iterable.forEach, Map.getOrDefault and putIfAbsent, and Files.lines for streaming a file's lines.
Senior and scenario questions
- A stream pipeline in a hot path is slower than the loop it replaced. What do you check? Boxing, an unnecessary sorted or distinct, a collector that builds intermediate lists, and whether it was made parallel. Measure with a proper benchmark harness before changing it.
- A service calls three APIs in sequence. How would you make it concurrent with Java 8? Start each with supplyAsync on a bounded executor sized for I/O, combine with allOf or thenCombine, add timeouts and a fallback per call, and make sure exceptions surface rather than vanish.
- Your team wants Optional on every getter. Do you agree? Not for fields or setters. Use it on return types where absence is a normal outcome, keep collections empty rather than optional, and do not call get without checking.
- A report shows the wrong day for users in another country. Where do you look? Code that used LocalDate.now() or the server's default zone instead of the user's zone, and timestamps stored as local times rather than Instants.
- How would you explain the benefits of upgrading from Java 8? Speak generally: newer releases bring language features, performance and security updates, and long-term support releases matter for planning. Check the specific release notes rather than quoting features from memory.
Fictional example
- Interviewer
- This loop goes through transactions, skips refunds, and builds a map from merchant to total amount. Rewrite it with streams. Would you merge it?
- Candidate
- I would filter out refunds, then collect with groupingBy on the merchant and summingDouble on the amount, or reducing over BigDecimal if these are real money values, since double loses cents. If the order of merchants matters in the output, I would pass a TreeMap or LinkedHashMap supplier. Whether to merge depends on the rest of the code. Here the stream is shorter and states the intent, so yes. If the loop also had early exits, logging per item or checked exceptions, I would keep the loop, because the stream version would hide those behind wrappers. I would also not make it parallel without measuring, since the input is small.
Java 8 practice plan
- Day 1: write ten small stream pipelines over a list of your own objects: group, partition, join strings, top three by value, and a toMap with duplicates.
- Day 2: take three loops from a real project and convert them, then decide for each which version is clearer and say why.
- Day 3: model a booking in java.time across two time zones and a daylight-saving change, and print every step.
- Day 4: call three slow methods with CompletableFuture on your own executor, add a timeout and a fallback, and break one on purpose.
- Day 5: explain laziness, effectively final, default method conflicts and Metaspace aloud in about a minute each.
Java 8 questions sit next to platform ones. J2EE interview questions cover the enterprise APIs these services often run on, Groovy interview questions cover the JVM scripting language many Java teams use in builds, and Spring Boot interview questions cover the framework layer.
When you narrate a stream pipeline aloud, it is easy to skip the reason for each step. Natively, an AI interview assistant for Mac and Windows, can transcribe a mock Java round on your computer so you can read back whether you explained laziness and collectors or just typed. During practice it can read a coding prompt or a compiler error from a screenshot and suggest an approach, and with Pro or the free trial it can draw on your résumé and the job description you add. Transcripts and notes are saved so you can review them before the next session.
Questions people ask
What Java 8 features are asked in interviews?
Lambdas and functional interfaces, method references, the Stream API and collectors, Optional, default and static interface methods, the java.time API, CompletableFuture, ConcurrentHashMap additions and Metaspace.
Why are Java streams called lazy?
Intermediate operations such as filter and map only describe the pipeline. Nothing runs until a terminal operation such as collect or findFirst pulls elements, and short-circuiting operations stop as soon as they have an answer.
What is the difference between map and flatMap in Java 8?
map turns each element into exactly one new element. flatMap turns each element into a stream and flattens all of them into one stream, which is how you expand nested lists.
Are Java 8 questions still asked for experienced developers?
Yes. Many production codebases use Java 8 features throughout, so experienced candidates are often asked to refactor loops into streams, compose CompletableFutures and fix date and time bugs.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
