Java 8 Interview Questions

Naveen AnamaneniUpdated · 6 min read

Many companies ran Java 8 for almost a decade, and even teams on Java 21 or 25 write code in the style Java 8 introduced: lambdas, streams and Optional. So "Java 8 questions" are really questions about modern everyday Java, and they show up in nearly every interview, often with a short stream problem to solve on the spot. This page collects the most common questions and the stream exercises interviewers like, from basic to advanced.

Basic Questions

What are the main features of Java 8?

Lambda expressions, functional interfaces, method references, the Stream API, Optional, default and static methods in interfaces, and the java.time date and time API. Also CompletableFuture, String.join and Metaspace replacing PermGen.

What is a lambda expression?

A short anonymous function that can be passed around as a value: (a, b) -> a + b. It implements the single abstract method of a functional interface, so the compiler knows its parameter and return types from context.

What is a functional interface?

An interface with exactly one abstract method, such as Runnable, Comparator or Function. @FunctionalInterface asks the compiler to check this. Default and static methods don't count.

Name the main built-in functional interfaces.

Predicate<T> (T → boolean), Function<T, R> (T → R), Consumer<T> (T → nothing), Supplier<T> (nothing → T), UnaryOperator<T> and BinaryOperator<T>, plus primitive versions such as IntPredicate.

What is a method reference?

A shorter form of a lambda that only calls an existing method: String::length, System.out::println, Student::new. There are four kinds: static, bound instance, unbound instance and constructor.

Intermediate Questions

What is the difference between intermediate and terminal stream operations?

Intermediate operations (filter, map, sorted, distinct) return a new stream and are lazy: nothing runs yet. A terminal operation (collect, forEach, count, reduce, findFirst) starts the pipeline and produces a result. A stream can be used only once.

What is the difference between map and flatMap?

map turns each element into one element. flatMap turns each element into a stream and joins all those streams into one, flattening nested structures: a list of classes, each with a list of students, becomes one stream of students.

What is Optional, and how should it be used?

A container that may or may not hold a value, used as a return type to say "there may be no result". Use orElse, orElseGet, orElseThrow, map and ifPresent; avoid get() without a check, and don't use Optional for fields or parameters.

Why were default methods added to interfaces?

So interfaces such as Collection could gain new methods (stream, forEach, removeIf) without breaking every existing class that implemented them.

What is the difference between findFirst and findAny?

findFirst returns the first element in encounter order. findAny may return any element, which lets parallel streams finish faster. On a sequential stream they usually return the same element, but only findFirst guarantees it.

Advanced Questions

What does "effectively final" mean for lambdas?

A lambda can use a local variable from the enclosing method only if that variable is never reassigned after it is set. The lambda captures its value, so allowing changes would create confusing, unsafe behavior.

When should you use parallel streams?

Only for large amounts of CPU-heavy, independent work on data that splits easily (arrays, ArrayList), with no shared mutable state, and after measuring. For small data or I/O, the overhead makes them slower.

What is the difference between Collectors.toList() and Stream.toList()?

Stream.toList() (Java 16) returns an unmodifiable list and is shorter. Collectors.toList() returns a list with no guarantee about mutability (in practice an ArrayList). Use Collectors.toCollection(ArrayList::new) when you need a list you can change.

How do you group and count with streams?

Collectors.groupingBy(classifier) builds a Map of lists; add a downstream collector to do more: groupingBy(Student::grade, Collectors.counting()) counts students per grade. partitioningBy splits into true and false groups.

Stream Problems Interviewers Ask

Let's see answers to five short stream problems in one program.

StreamProblems.java▶ Try it
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
 
public class StreamProblems {
    record Student(String name, String grade, int marks) {}
 
    public static void main(String[] args) {
        List<Student> students = List.of(
                new Student("Navika", "A", 91),
                new Student("Srihitha", "B", 78),
                new Student("Advitha", "A", 88),
                new Student("Navika Anamaneni", "C", 64));
 
        // 1. Names of students with marks above 80, sorted
        System.out.println(students.stream()
                .filter(s -> s.marks() > 80)
                .map(Student::name)
                .sorted()
                .toList());
 
        // 2. Count students per grade
        Map<String, Long> perGrade = students.stream()
                .collect(Collectors.groupingBy(Student::grade,
                        TreeMap::new, Collectors.counting()));
        System.out.println(perGrade);
 
        // 3. Topper
        students.stream()
                .max(Comparator.comparingInt(Student::marks))
                .ifPresent(s -> System.out.println("topper: " + s.name()));
 
        // 4. First non-repeated character in a word
        String word = "srihitha";
        Map<Character, Long> counts = word.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(),
                        LinkedHashMap::new, Collectors.counting()));
        counts.entrySet().stream()
                .filter(e -> e.getValue() == 1)
                .findFirst()
                .ifPresent(e -> System.out.println("first unique: "
                        + e.getKey()));
 
        // 5. Sum of squares of even numbers from 1 to 10
        System.out.println(IntStream.rangeClosed(1, 10)
                .filter(n -> n % 2 == 0)
                .map(n -> n * n)
                .sum());
    }
}
Output
[Advitha, Navika]
{A=2, B=1, C=1}
topper: Navika
first unique: s
220

Explanation:

  1. Filter, map, sort, collect is the most common pipeline shape.
  2. groupingBy with TreeMap::new keeps grades in order, and counting() counts each group.
  3. max with a comparator returns an Optional, handled with ifPresent.
  4. A LinkedHashMap keeps characters in first-seen order, so the first entry with a count of 1 is the answer.
  5. IntStream avoids boxing for number crunching.

Interview Corner

How do you explain the benefit of streams over loops?

Streams say what you want (filter, map, collect) instead of how to loop, so pipelines are shorter and easier to read, can be parallelized with one call, and avoid manual index and temporary-list bugs. Loops remain fine, and sometimes clearer, for simple cases or early exits with complex logic.

Practice

  1. Easy: From a list of names, use a stream to make a comma-separated string of the names in uppercase: Collectors.joining(", ").
  2. Harder: Given List<List<Integer>> classes = List.of(List.of(91, 78), List.of(88), List.of(64, 99)), use flatMap to find the overall average mark.

Quick check: Java 8

4 questions
1Which operation starts a stream pipeline running?
2What does flatMap do?
3Which is a Supplier?
4What does Stream.toList() return?

Key Takeaways

Was this tutorial helpful?

Lesson 575 of 578