GamifiedGamified challengesPracticeRaceLeaderboardPricing

Learn data structures by watching them move, then doing it yourself. Press M anytime to toggle sound.

A product of Amypo Technologies, Coimbatore.

Learn

  • All topics
  • Learning path
  • How it works
  • About dotprep

Practice

  • Practice arena
  • Daily challenge
  • Gamified challenges
  • Race mode
  • Leaderboard

Interview prep

  • Java interview
  • Coding questions
  • Company questions
  • System design
  • Jobs & careers

You

  • Dashboard
  • Settings
  • Pricing
  • Create account

© 2026 dotprep

Content last updated 20 November 2026

GamifiedGamified challengesPracticeRaceLeaderboardPricing
Java interviewJava 8+ features

Java 8+ features

Lambdas, functional interfaces, streams, Optional, and the modern additions: records, var, switch expressions and sealed types.

intermediate 20 min read 8 interview questions

On this page

1/6
  1. 01Lambdas and functional interfaces
  2. 02Streams
  3. 03Optional
  4. 04Modern Java: records, var, switch, sealed, text blocks
  5. 05Interview questions
  6. 06Quick check
Back to top

Lambdas and functional interfaces

A functional interface has exactly one abstract method (@FunctionalInterface makes the compiler check). A lambda is a short way to implement it; a method reference is shorter still when a method already does the job.

java
Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());
Function<String, Integer> len = String::length; // method reference
Supplier<List<String>> fresh = ArrayList::new; // constructor reference
Predicate<String> empty = String::isEmpty;
Consumer<String> print = System.out::println;
InterfaceMethodShape
Function<T,R>applyT → R
Predicate<T>testT → boolean
Consumer<T>acceptT → void
Supplier<T>get() → T
UnaryOperator<T> / BinaryOperator<T>applyT → T / (T, T) → T

Lambdas can only use local variables that are effectively final (never reassigned after initialization).

Streams

A stream is a pipeline over data: a source, any number of intermediate operations (lazy: filter, map, sorted, distinct), and one terminal operation (collect, count, forEach, reduce) that actually runs it. A stream can be consumed only once.

java
record Emp(String name, String dept, double salary) {}
List<String> richNames = emps.stream()
.filter(e -> e.salary() > 100_000)
.map(Emp::name)
.sorted()
.toList(); // Java 16+
Map<String, Double> avgByDept = emps.stream()
.collect(Collectors.groupingBy(Emp::dept, Collectors.averagingDouble(Emp::salary)));
Optional<Emp> top = emps.stream().max(Comparator.comparingDouble(Emp::salary));
int total = IntStream.rangeClosed(1, 100).sum(); // primitive stream, no boxing
  • map turns each element into one element; flatMap turns each into a stream and flattens them.
  • Short-circuiting ops (findFirst, anyMatch, limit) stop early.
  • parallelStream() splits work across the common ForkJoin pool: only worth it for large, CPU-bound, side-effect-free work.

Optional

Optional<T> makes "there may be no value" explicit in a return type, instead of returning null.

java
Optional<User> user = repo.findByEmail(email);
String name = user.map(User::name).orElse("guest");
user.ifPresent(u -> mailer.welcome(u));
User u = user.orElseThrow(() -> new NotFoundException(email));

Use Optional for return values. Avoid it for fields, parameters or collections (return an empty list instead), and never call get() without checking.

Modern Java: records, var, switch, sealed, text blocks

java
record Money(String currency, long cents) { // Java 16: immutable data carrier
Money { if (cents < 0) throw new IllegalArgumentException(); } // compact constructor
}
var items = new ArrayList<String>(); // Java 10: local type inference
String kind = switch (day) { // Java 14: switch expression
case SATURDAY, SUNDAY -> "weekend";
default -> "weekday";
};
sealed interface Shape permits Circle, Square {} // Java 17: closed hierarchy
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
double area = switch (shape) { // Java 21: pattern matching for switch
case Circle c -> Math.PI * c.r() * c.r();
case Square s -> s.side() * s.side();
}; // no default needed: sealed
String json = """
{ "name": "Ada" }
"""; // Java 15: text block

Interview questions

Try answering out loud first, then open the model answer.

Q1What is a functional interface? Name some built-in ones.beginner

An interface with exactly one abstract method, so it can be implemented by a lambda. Built-ins: Runnable, Comparator, Function, Predicate, Consumer, Supplier, BiFunction. It may still have default and static methods.

Q2Intermediate vs terminal stream operations?beginner

Intermediate operations (filter, map, sorted) return a new stream and are lazy: nothing runs until a terminal operation (collect, forEach, count, reduce) is called. After the terminal operation the stream is consumed.

Q3map vs flatMap?intermediate

map transforms each element into exactly one element. flatMap transforms each element into a stream and concatenates them, e.g. sentences.stream().flatMap(s -> Arrays.stream(s.split(" "))) gives all words.

Q4How do you group a list of employees by department and count them?intermediate
java
Map<String, Long> counts = emps.stream()
.collect(Collectors.groupingBy(Emp::dept, Collectors.counting()));
Q5Why use Optional and what are common misuses?intermediate

It makes absence explicit in an API and offers fluent handling (map, orElse, orElseThrow). Misuses: calling get() without checking, using it for fields or parameters, wrapping collections, or Optional.of(null) (use ofNullable).

Q6What is a record?intermediate

A concise immutable data class (Java 16). record Point(int x, int y) {} generates private final fields, a canonical constructor, accessors x()/y(), and equals, hashCode, toString. Records can't extend classes but can implement interfaces and add methods.

Q7When should you use parallel streams?advanced

Only for large datasets with CPU-heavy, independent, side-effect-free work and sources that split well (arrays, ArrayList, ranges). They share the common ForkJoin pool, so blocking I/O in them hurts the whole app. Measure first.

Q8What are default methods and why were they added?intermediate

Interface methods with a body. They let Java 8 add methods like forEach and stream() to existing interfaces such as Collection without breaking every class that implements them. If two interfaces supply the same default method, the class must override it.

Quick check

Question 1

1.Which operation makes a stream pipeline actually run?

Question 2

2.Predicate<T> represents…

Question 3

3.A record's fields are…

Question 4

4.Which flattens a stream of lists into one stream?

0 of 4 answered

GenericsMultithreading & concurrency
Log inStart free