Key takeaways
- Java 8 is still the most asked Java topic for 3–8 years experience: lambdas, functional interfaces, streams and
Optional. - Expect live stream coding: group employees by department, find the second-highest salary, count characters, find duplicates.
- Senior rounds probe laziness,
mapvsflatMap, collectors, parallel streams and when not to use streams.
Java 8 changed how Java is written, and almost a decade later it is still the most common topic in experienced Java interviews. Interviewers use it to check whether you write clean, functional-style code — and to set live stream coding problems. Here are the most asked Java 8 interview questions for experienced developers, with code. The full Java interview questions page covers collections, concurrency, the JVM and more.
Lambdas and functional interfaces
What is a functional interface? Name the important built-in ones.
An interface with exactly one abstract method, which a lambda or method reference can implement. @FunctionalInterface makes the compiler enforce it. The key ones in java.util.function:
| Interface | Method | Example use |
|---|---|---|
Predicate<T> | boolean test(T) | filtering |
Function<T,R> | R apply(T) | mapping |
Consumer<T> | void accept(T) | forEach |
Supplier<T> | T get() | lazy defaults, factories |
BiFunction<T,U,R> | R apply(T,U) | merge, reduce |
UnaryOperator<T> / BinaryOperator<T> | same type in and out | replaceAll, reduce |
Why can lambdas only use "effectively final" local variables?
A lambda may run later or on another thread, so it captures a copy of each local variable's value. To prevent confusing results, Java requires captured locals to be final or effectively final (never reassigned). Instance fields can be modified because they are reached through this, but mutating shared state from lambdas is a classic concurrency bug.
What are default and static methods in interfaces, and why were they added?
Default methods let an interface add new methods with an implementation without breaking existing implementations — that's how Collection.stream() and List.sort() were added in Java 8. Static methods hold helper code on the interface itself (Comparator.comparing). If a class inherits two conflicting defaults, it must override the method, and can call one with A.super.method().
Streams
What is the difference between intermediate and terminal operations? What does "lazy" mean?
- Intermediate operations (
filter,map,sorted,distinct,limit) return a new stream and are lazy — nothing runs yet. - Terminal operations (
collect,forEach,reduce,count,findFirst) trigger processing.
Because of laziness, elements flow through the pipeline one at a time, and short-circuiting operations stop early:
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
int first = nums.stream()
.filter(n -> { System.out.println("filter " + n); return n % 2 == 0; })
.map(n -> n * n)
.findFirst() // stops after the first match
.orElse(-1);
// prints only: filter 1, filter 2 → first == 4What is the difference between map and flatMap?
map transforms each element one to one. flatMap maps each element to a stream and flattens the results into one stream — use it for nested collections.
List<List<String>> teams = List.of(List.of("Asha", "Ravi"), List.of("Meera"));
List<Integer> sizes = teams.stream().map(List::size).toList(); // [2, 1]
List<String> people = teams.stream().flatMap(List::stream).toList(); // [Asha, Ravi, Meera]toList() arrived in Java 16. On Java 8, use collect(Collectors.toList()).
How do groupingBy, partitioningBy and toMap work?
record Employee(String name, String dept, double salary) {}
List<Employee> emps = List.of(
new Employee("Asha", "Eng", 120_000), new Employee("Ravi", "Eng", 95_000),
new Employee("Meera", "HR", 70_000), new Employee("Kabir", "Sales", 80_000));
// Count per department
Map<String, Long> countByDept = emps.stream()
.collect(Collectors.groupingBy(Employee::dept, Collectors.counting()));
// {Sales=1, HR=1, Eng=2} — HashMap order is not guaranteed
// Average salary per department
Map<String, Double> avgByDept = emps.stream()
.collect(Collectors.groupingBy(Employee::dept, Collectors.averagingDouble(Employee::salary)));
// Split into two groups by a condition
Map<Boolean, List<String>> highEarners = emps.stream()
.collect(Collectors.partitioningBy(e -> e.salary() > 90_000,
Collectors.mapping(Employee::name, Collectors.toList())));
// {false=[Meera, Kabir], true=[Asha, Ravi]}
// toMap with a merge function for duplicate keys (otherwise IllegalStateException)
Map<String, Double> maxSalaryByDept = emps.stream()
.collect(Collectors.toMap(Employee::dept, Employee::salary, Math::max));When should you use parallel streams — and when not?
Parallel streams split work across the common ForkJoinPool. They can help for CPU-heavy work on large data with no shared state. Avoid them for small collections, I/O or blocking calls (they starve the shared pool), order-dependent logic, and code that mutates shared state. Always measure with a benchmark (JMH) — parallel is often slower for typical business code.
Optional
What is Optional, and what are the best practices?
Optional<T> makes "may be absent" explicit in a return type, instead of returning null.
Do:
- Return
Optionalfrom methods likefindById. - Chain with
map,filter,orElse,orElseGetandorElseThrow.
Don't:
- Use it for fields, method parameters or collections — return an empty list instead.
- Call
get()without checking.
Optional<Employee> found = emps.stream().filter(e -> e.name().equals("Ravi")).findFirst();
String dept = found.map(Employee::dept).orElse("Unknown");
Employee e = found.orElseThrow(() -> new IllegalArgumentException("not found"));Stream coding questions
Find the second-highest salary using streams.
Optional<Double> secondHighest = emps.stream()
.map(Employee::salary)
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();
// Optional[95000.0]Count the frequency of each character in a string.
String s = "interview";
Map<Character, Long> freq = s.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
// {i=2, n=1, t=1, e=2, r=1, v=1, w=1}Find duplicate elements in a list.
List<Integer> nums = List.of(1, 2, 3, 2, 4, 3, 5);
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = nums.stream()
.filter(n -> !seen.add(n)) // add() returns false if already present
.collect(Collectors.toSet()); // [2, 3]Find the employee with the highest salary in each department.
Map<String, Optional<Employee>> topByDept = emps.stream()
.collect(Collectors.groupingBy(Employee::dept,
Collectors.maxBy(Comparator.comparingDouble(Employee::salary))));
// Eng → Asha, HR → Meera, Sales → KabirKeep practising
- 56 core Java questions, from OOP to the JVM: Java interview questions with answers
- Test yourself: free Java quiz
- Plan your preparation: programming interview preparation roadmap