0% found this document useful (0 votes)
2 views15 pages

Java8 Interview CodingCheatSheet

This document is a Java 8 coding interview cheat sheet designed for candidates with over 7 years of experience. It covers various topics including Streams, Lambdas, Optional, Collectors, and Parallel Streams, providing coding questions and answers for each topic. The cheat sheet includes practical examples and best practices for using Java 8 features effectively in coding interviews.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Java8 Interview CodingCheatSheet

This document is a Java 8 coding interview cheat sheet designed for candidates with over 7 years of experience. It covers various topics including Streams, Lambdas, Optional, Collectors, and Parallel Streams, providing coding questions and answers for each topic. The cheat sheet includes practical examples and best practices for using Java 8 features effectively in coding interviews.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 1

☕ JAVA 8 CODING INTERVIEW


CHEAT SHEET | Senior / 7+ Years
Streams · Lambdas · Functional Interfaces · Optional · Collectors · Parallel Streams · Date/Time · Completable Futures

1. STREAMS — Coding Questions

Q1. Find all employees with salary > 50000, sort by name, return list of names.
✔ Answer:
List<String> result = [Link]()
.filter(e -> [Link]() > 50000)
.sorted([Link](Employee::getName))
.map(Employee::getName)
.collect([Link]());
💡 filter → sorted → map → collect is the standard pipeline pattern.

Q2. Find the second highest salary from a list of employees.


✔ Answer:
Optional<Double> secondHighest = [Link]()
.map(Employee::getSalary)
.distinct()
.sorted([Link]())
.skip(1)
.findFirst();
💡 distinct() is crucial — without it you may get the same max salary twice.

Q3. Group employees by department and count each group.


✔ Answer:
Map<String, Long> countByDept = [Link]()
.collect([Link](
Employee::getDepartment,
[Link]()
));

Q4. Group employees by department and get average salary per department.
✔ Answer:
Map<String, Double> avgSalary = [Link]()
.collect([Link](
Employee::getDepartment,
[Link](Employee::getSalary)
));

Q5. Find the department with the highest total salary bill.
✔ Answer:
Optional<[Link]<String, Double>> topDept = [Link]()
.collect([Link](
Employee::getDepartment,
[Link](Employee::getSalary)
))
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 2
.entrySet().stream()
.max([Link]());

Q6. Flatten a List<List<Integer>> into a single sorted list without duplicates.


✔ Answer:
List<Integer> flat = [Link]()
.flatMap(Collection::stream)
.distinct()
.sorted()
.collect([Link]());
💡 flatMap is the key — it replaces each element with a stream of elements.

Q7. Partition employees into those who earn above average and those who don't.
✔ Answer:
double avg = [Link]()
.mapToDouble(Employee::getSalary).average().orElse(0);

Map<Boolean, List<Employee>> partitioned = [Link]()


.collect([Link](e -> [Link]() > avg));

// true -> above average


// false -> at or below average

Q8. Count the frequency of each character in a String using streams.


✔ Answer:
String s = "interview";
Map<Character, Long> freq = [Link]()
.mapToObj(c -> (char) c)
.collect([Link](c -> c, [Link]()));

Q9. Joining a list of strings with delimiter, prefix and suffix.


✔ Answer:
List<String> names = [Link]("Alice", "Bob", "Carol");
String result = [Link]()
.collect([Link](", ", "[", "]"));
// Output: [Alice, Bob, Carol]

Q10. Find the first non-repeated character in a string using streams.


✔ Answer:
String s = "swiss";
Optional<Character> result = [Link]()
.mapToObj(c -> (char) c)
.collect([Link](c -> c, LinkedHashMap::new, [Link]()))
.entrySet().stream()
.filter(e -> [Link]() == 1)
.map([Link]::getKey)
.findFirst();
// Result: w
💡 LinkedHashMap preserves insertion order, essential here.

Q11. Convert a List<String> to a Map<String, Integer> (string → its length).


✔ Answer:
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 3
List<String> words = [Link]("java", "stream", "api");
Map<String, Integer> map = [Link]()
.collect([Link](
s -> s,
String::length
));
// Duplicate key? Add merge function: (v1, v2) -> v1

Q12. Sum of squares of even numbers in a list.


✔ Answer:
List<Integer> nums = [Link](1, 2, 3, 4, 5, 6);
int sumOfSquares = [Link]()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * n)
.sum();
// Result: 4 + 16 + 36 = 56

Q13. Demonstrate reduce() — product of all numbers in a list.


✔ Answer:
List<Integer> nums = [Link](1, 2, 3, 4, 5);
int product = [Link]()
.reduce(1, (a, b) -> a * b);
// Result: 120

// reduce with no identity returns Optional:


Optional<Integer> sum = [Link]().reduce(Integer::sum);

Q14. Get top 3 highest-paid employees per department.


✔ Answer:
Map<String, List<Employee>> top3ByDept = [Link]()
.collect([Link](
Employee::getDepartment,
[Link](
[Link](),
list -> [Link]()
.sorted([Link](Employee::getSalary).reversed())
.limit(3)
.collect([Link]())
)
));

Q15. Check if all / any / none elements satisfy a condition.


✔ Answer:
List<Integer> nums = [Link](2, 4, 6, 8);
boolean allEven = [Link]().allMatch(n -> n % 2 == 0); // true
boolean anyAbove5 = [Link]().anyMatch(n -> n > 5); // true
boolean noneNeg = [Link]().noneMatch(n -> n < 0); // true

2. LAMBDA EXPRESSIONS — Coding Questions

Q16. Sort a list of strings by length, then alphabetically using lambda.


Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 4
✔ Answer:
List<String> words = new ArrayList<>([Link]("banana", "fig", "apple", "kiwi"));
[Link]([Link](String::length)
.thenComparing([Link]()));
// [fig, kiwi, apple, banana]

Q17. Write a generic Comparator using lambda to sort by multiple fields.


✔ Answer:
[Link]([Link](Employee::getDepartment)
.thenComparing(Employee::getName)
.thenComparingDouble(Employee::getSalary).reversed());

Q18. Implement a custom functional interface and use it with a lambda.


✔ Answer:
@FunctionalInterface
interface Transformer<T, R> {
R transform(T input);
// Can have default & static methods — still functional!
}

Transformer<String, Integer> strLen = s -> [Link]();


[Link]([Link]("Java 8")); // 6

Q19. Use method references — static, instance, constructor.


✔ Answer:
// Static method reference
Function<String, Integer> parseInt = Integer::parseInt;

// Instance method reference (specific instance)


String prefix = "Hello";
Predicate<String> startsWithHello = prefix::equals;

// Instance method reference (arbitrary instance)


Function<String, String> toUpper = String::toUpperCase;

// Constructor reference
Supplier<ArrayList<String>> listFactory = ArrayList::new;

Q20. Demonstrate [Link]() and [Link]() chaining.


✔ Answer:
Function<Integer, Integer> doubleIt = x -> x * 2;
Function<Integer, Integer> addTen = x -> x + 10;

// andThen: doubleIt first, then addTen


Function<Integer, Integer> doubleThenAdd = [Link](addTen);
[Link]([Link](5)); // (5*2)+10 = 20

// compose: addTen first, then doubleIt


Function<Integer, Integer> addThenDouble = [Link](addTen);
[Link]([Link](5)); // (5+10)*2 = 30

Q21. Use [Link](), [Link](), [Link]().


✔ Answer:
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 5
Predicate<Integer> isEven = n -> n % 2 == 0;
Predicate<Integer> isPositive = n -> n > 0;

Predicate<Integer> isEvenAndPositive = [Link](isPositive);


Predicate<Integer> isEvenOrPositive = [Link](isPositive);
Predicate<Integer> isOdd = [Link]();

[Link]([Link](4)); // true
[Link]([Link](-3)); // false
[Link]([Link](7)); // true

Q22. BiFunction, BiPredicate, BiConsumer examples.


✔ Answer:
BiFunction<String, Integer, String> repeat = (s, n) -> [Link](n);
BiPredicate<String, String> startsWith = String::startsWith;
BiConsumer<String, Integer> printer = (s, i) -> [Link](s + i);

[Link]([Link]("hi", 3)); // hihihi


[Link]([Link]("Java8", "Java")); // true
[Link]("Count: ", 42); // Count: 42

3. OPTIONAL — Coding Questions

Q23. Safely get a value or default without NullPointerException.


✔ Answer:
Optional<String> name = [Link](getUserName());

// orElse — always evaluates the default


String n1 = [Link]("Anonymous");

// orElseGet — lazy, only evaluates supplier if empty (preferred for costly ops)
String n2 = [Link](() -> fetchDefaultName());

// orElseThrow
String n3 = [Link](() -> new UserNotFoundException("No user found"));

Q24. Chain Optional with map and flatMap.


✔ Answer:
// map wraps result in Optional automatically
Optional<Integer> nameLength = [Link](user)
.map(User::getName)
.map(String::length);

// flatMap — use when the mapper itself returns Optional


Optional<String> city = [Link](user)
.flatMap(User::getAddress) // returns Optional<Address>
.flatMap(Address::getCity); // returns Optional<String>
💡 Never use get() without isPresent(). Always prefer map/flatMap/orElse patterns.

Q25. Filter an Optional value.


✔ Answer:
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 6
Optional<String> email = [Link](getEmail())
.filter(e -> [Link]("@"));

// Returns empty Optional if predicate fails


[Link]([Link]::println);

// Java 9+ ifPresentOrElse:
[Link](
e -> [Link]("Email: " + e),
() -> [Link]("No valid email")
);

Q26. Return Optional from a repository method — best practice.


✔ Answer:
public Optional<Employee> findById(int id) {
return [Link]()
.filter(e -> [Link]() == id)
.findFirst(); // Already returns Optional<Employee>
}

// Caller:
String name = [Link](42)
.map(Employee::getName)
.orElse("Not Found");

4. COLLECTORS — Advanced Coding Questions

Q27. Implement a custom Collector to join strings with prefix/suffix.


✔ Answer:
// Built-in — know this first:
String result = [Link]("a","b","c")
.collect([Link](", ", "{", "}"));
// {a, b, c}

// Custom Collector (demonstrates the pattern):


Collector<String, StringBuilder, String> customJoiner =
[Link](
StringBuilder::new,
(sb, s) -> [Link](s).append("|"),
StringBuilder::append,
sb -> "[" + [Link]() + "]"
);

String r = [Link]("x","y","z").collect(customJoiner);
// [x|y|z|]

Q28. toUnmodifiableMap and handling duplicate keys.


✔ Answer:
// With merge function for duplicate keys
Map<String, Double> salaryMap = [Link]()
.collect([Link](
Employee::getName,
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 7
Employee::getSalary,
(existing, newVal) -> existing, // keep first on dup
LinkedHashMap::new // maintain order
));

// Java 10+ unmodifiable


Map<String, Double> immutable = [Link]()
.collect([Link](
Employee::getName, Employee::getSalary
));

Q29. Downstream collectors — summarizing statistics.


✔ Answer:
Map<String, DoubleSummaryStatistics> statsByDept = [Link]()
.collect([Link](
Employee::getDepartment,
[Link](Employee::getSalary)
));

[Link]((dept, stats) -> {


[Link]("%s -> min=%.0f, max=%.0f, avg=%.0f, count=%d%n",
dept, [Link](), [Link](),
[Link](), [Link]());
});

Q30. Multi-level grouping (group by dept, then by city).


✔ Answer:
Map<String, Map<String, List<Employee>>> multiGroup = [Link]()
.collect([Link](
Employee::getDepartment,
[Link](Employee::getCity)
));

5. PARALLEL STREAMS — Coding Questions

Q31. When to use parallel streams — demonstrate a safe usage.


✔ Answer:
// Safe: stateless, non-interfering, associative operation
long count = [Link](1, 1_000_000)
.parallel()
.filter(n -> n % 2 == 0)
.count();

// UNSAFE: shared mutable state — NEVER do this


List<Integer> result = new ArrayList<>();
[Link]().forEach(result::add); // Race condition!

// SAFE equivalent:
List<Integer> safe = [Link]()
.collect([Link]()); // Thread-safe collect
💡 Use parallel streams for CPU-intensive, large data (>10K elements), no shared state, and associative ops.
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 8
Q32. Sum 1 to 10 million using parallel IntStream.
✔ Answer:
long sum = [Link](1, 10_000_000)
.parallel()
.asLongStream() // prevent int overflow
.sum();
[Link](sum); // 50000005000000

Q33. Pitfall — parallel stream with forEach ordering.


✔ Answer:
// Unordered output (non-deterministic)
[Link](1,2,3,4,5).parallelStream().forEach([Link]::println);

// Ordered output — use forEachOrdered (loses some parallelism benefit)


[Link](1,2,3,4,5).parallelStream().forEachOrdered([Link]::println);

// collect() is always order-preserving for ordered sources:


List<Integer> ordered = [Link](5,3,1,4,2).parallelStream()
.sorted().collect([Link]()); // [1,2,3,4,5]

6. BUILT-IN FUNCTIONAL INTERFACES — Quick-fire Coding

Q34. Demonstrate all four core functional interfaces in one example.


✔ Answer:
// Supplier<T> — no input, returns T
Supplier<LocalDate> today = LocalDate::now;

// Consumer<T> — takes T, returns void


Consumer<String> printer = [Link]::println;

// Function<T,R> — takes T, returns R


Function<String, Integer> len = String::length;

// Predicate<T> — takes T, returns boolean


Predicate<String> isEmpty = String::isEmpty;

// Chained usage:
[Link]("Hello")
.filter([Link]())
.map(len)
.ifPresent([Link](n -> {})); // prints 5

Q35. UnaryOperator and BinaryOperator examples.


✔ Answer:
// UnaryOperator<T> extends Function<T, T>
UnaryOperator<String> trim = String::trim;
UnaryOperator<Integer> square = x -> x * x;

// BinaryOperator<T> extends BiFunction<T, T, T>


BinaryOperator<Integer> max = Integer::max;
BinaryOperator<String> concat = String::concat;
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 9
// In streams:
List<String> cleaned = [Link]()
.map(trim).collect([Link]());

int result = [Link]().reduce(0, Integer::sum); // BinaryOperator

7. DATE / TIME API — Coding Questions

Q36. Calculate number of days between two dates.


✔ Answer:
LocalDate start = [Link](2024, 1, 1);
LocalDate end = [Link](2024, 12, 31);

long days = [Link](start, end); // 365

// Period for human-readable diff:


Period p = [Link](start, end);
[Link]("%d months and %d days%n", [Link](), [Link]());

Q37. Get the next Monday from today; find all Fridays in a month.
✔ Answer:
LocalDate today = [Link]();

// Next Monday
LocalDate nextMonday = [Link]([Link]([Link]));

// All Fridays in March 2024


LocalDate firstFriday = [Link](2024, 3, 1)
.with([Link]([Link]));

List<LocalDate> fridays = [Link](firstFriday, d -> [Link](1))


.takeWhile(d -> [Link]() == [Link]())
.collect([Link]());

Q38. Convert between LocalDateTime and legacy Date/Instant.


✔ Answer:
// LocalDateTime -> Instant -> Date
LocalDateTime ldt = [Link]();
Instant instant = [Link]([Link]);
Date legacyDate = [Link](instant);

// Date -> Instant -> LocalDateTime


Date old = new Date();
LocalDateTime newLdt = [Link]()
.atZone([Link]())
.toLocalDateTime();

Q39. Format and parse dates using DateTimeFormatter.


✔ Answer:
// Format
LocalDate date = [Link](2024, 6, 15);
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 10
DateTimeFormatter fmt = [Link]("dd-MMM-yyyy");
String formatted = [Link](fmt); // "15-Jun-2024"

// Parse
LocalDate parsed = [Link]("15-Jun-2024", fmt);

// Thread-safe — DateTimeFormatter is immutable (unlike SimpleDateFormat!)


DateTimeFormatter iso = DateTimeFormatter.ISO_LOCAL_DATE;
String isoStr = [Link]().format(iso); // "2024-06-15"
💡 SimpleDateFormat is NOT thread-safe. DateTimeFormatter IS — always prefer it.

8. COMPLETABLEFUTURE — Async Coding Questions

Q40. Run a task asynchronously and get the result.


✔ Answer:
// supplyAsync — returns a value
CompletableFuture<String> future = [Link](() -> {
// Simulating DB call
return fetchUserFromDB(userId);
});

// runAsync — no return value


CompletableFuture<Void> fire = [Link](() -> {
sendEmail(user);
});

// Block and get (avoid in production — prefer thenApply chain)


String user = [Link](5, [Link]);

Q41. Chain multiple async tasks with thenApply, thenCompose, thenAccept.


✔ Answer:
// thenApply — transforms result (synchronous)
CompletableFuture<Integer> nameLen = CompletableFuture
.supplyAsync(() -> "Java 8")
.thenApply(String::length); // runs in same thread pool

// thenCompose — chains another async task (flatMap for CF)


CompletableFuture<String> pipeline = CompletableFuture
.supplyAsync(() -> fetchUserId())
.thenCompose(id -> [Link](() -> fetchUser(id)));

// thenAccept — consume result, return Void


[Link](user -> [Link]("Got user: " + user));

Q42. Run two futures in parallel and combine results (thenCombine).


✔ Answer:
CompletableFuture<String> userFuture = [Link](this::fetchUser);
CompletableFuture<String> orderFuture = [Link](this::fetchOrders);

CompletableFuture<String> combined = [Link](


orderFuture,
(user, orders) -> user + " | " + orders
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 11
);

// Wait for ALL:


[Link](userFuture, orderFuture).join();

// Wait for FIRST:


[Link](userFuture, orderFuture)
.thenAccept(result -> [Link]("First done: " + result));

Q43. Exception handling in CompletableFuture.


✔ Answer:
CompletableFuture<String> safe = CompletableFuture
.supplyAsync(() -> fetchUser(id))
.exceptionally(ex -> {
[Link]("Failed", ex);
return "default-user"; // fallback value
});

// handle — always runs, whether success or failure


CompletableFuture<String> handled = CompletableFuture
.supplyAsync(() -> fetchUser(id))
.handle((result, ex) -> ex != null ? "error: " + [Link]() : result);

9. STRING & COLLECTIONS — Java 8 API Coding

Q44. Remove duplicates from a list preserving order.


✔ Answer:
List<Integer> withDups = [Link](3, 1, 4, 1, 5, 9, 2, 6, 5, 3);

// Stream distinct (uses equals/hashCode)


List<Integer> distinct = [Link]()
.distinct()
.collect([Link]()); // [3, 1, 4, 5, 9, 2, 6]

// Via LinkedHashSet (insertion-order)


List<Integer> distinct2 = new ArrayList<>(new LinkedHashSet<>(withDups));

Q45. [Link], computeIfAbsent, merge.


✔ Answer:
Map<String, List<String>> groups = new HashMap<>();

// computeIfAbsent — create value only if key absent


[Link]("fruits", k -> new ArrayList<>()).add("apple");
[Link]("fruits", k -> new ArrayList<>()).add("mango");
// {fruits=[apple, mango]}

// merge — combine old and new values


Map<String, Integer> wordCount = new HashMap<>();
String[] words = {"java", "is", "java"};
for (String w : words)
[Link](w, 1, Integer::sum);
// {java=2, is=1}
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 12

// getOrDefault
int count = [Link]("python", 0); // 0

Q46. [Link], chars(), lines() (Java 8+).


✔ Answer:
// [Link]
String csv = [Link](",", "a", "b", "c"); // a,b,c
String joined = [Link]("-", [Link]("2024","06","15")); // 2024-06-15

// chars() — stream of int codepoints


long upperCount = "Hello World".chars()
.filter(Character::isUpperCase).count(); // 2

// Reverse a string
String rev = new StringBuilder("java").reverse().toString(); // avaj

// Check palindrome
String s = "racecar";
boolean isPalin = [Link](0, [Link]() / 2)
.allMatch(i -> [Link](i) == [Link]([Link]() - 1 - i));

Q47. Find duplicates in a list using streams.


✔ Answer:
List<Integer> nums = [Link](1, 2, 3, 2, 4, 3, 5);

Set<Integer> seen = new HashSet<>();


Set<Integer> duplicates = [Link]()
.filter(n -> ![Link](n)) // add returns false if already present
.collect([Link]());
// {2, 3}

Q48. Iterate a Map using forEach with lambda (Java 8).


✔ Answer:
Map<String, Integer> scores = [Link]("Alice",95, "Bob",87, "Carol",92);

// forEach
[Link]((name, score) ->
[Link]("%-10s: %d%n", name, score));

// Sort by value, then print


[Link]().stream()
.sorted([Link].<String, Integer>comparingByValue().reversed())
.forEach(e -> [Link]([Link]() + " -> " + [Link]()));

10. TRICKY & ADVANCED — Senior-Level Questions

Q49. Infinite stream — generate Fibonacci numbers lazily.


✔ Answer:
// Using iterate (Java 9 has better overload, but Java 8 works too):
[Link](new long[]{0, 1}, f -> new long[]{f[1], f[0] + f[1]})
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 13
.limit(10)
.map(f -> f[0])
.forEach([Link]::println);
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

// Using [Link] with a stateful supplier (not pure):


long[] fib = {0, 1};
[Link](() -> { long v = fib[0]; fib[0] = fib[1]; fib[1] += v; return v; })
.limit(10).forEach([Link]::println);

Q50. Explain and fix a common stream reuse bug.


✔ Answer:
// BUG: Streams are single-use!
Stream<String> s = [Link]().filter(x -> [Link]("J"));
[Link]([Link]::println); // OK
[Link](); // THROWS IllegalStateException: stream has already been operated upon

// FIX 1: Use a Supplier


Supplier<Stream<String>> streamSupplier =
() -> [Link]().filter(x -> [Link]("J"));
[Link]().forEach([Link]::println); // fresh each time
long count = [Link]().count();

Q51. Demonstrate peek() for debugging without changing the pipeline.


✔ Answer:
List<String> result = [Link]("alice", "bob", "charlie", "dave")
.filter(s -> [Link]() > 3)
.peek(s -> [Link]("After filter: " + s))
.map(String::toUpperCase)
.peek(s -> [Link]("After map: " + s))
.collect([Link]());

// peek() does NOT transform — only observe


// NEVER rely on peek for side effects in production code

Q52. Implement word frequency counter from a paragraph.


✔ Answer:
String paragraph = "to be or not to be that is the question to";

Map<String, Long> freq = [Link]([Link]("\\s+"))


.collect([Link](
[Link](),
[Link]()
));

// Top 3 most frequent words:


[Link]().stream()
.sorted([Link].<String, Long>comparingByValue().reversed())
.limit(3)
.forEach(e -> [Link]([Link]() + " = " + [Link]()));
// to=3, be=2, or=1

Q53. Convert nested Map<String, List<Employee>> to flat list sorted by salary.


✔ Answer:
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 14
Map<String, List<Employee>> deptMap = ...; // dept -> employees

List<Employee> allSorted = [Link]().stream()


.flatMap(Collection::stream)
.sorted([Link](Employee::getSalary).reversed())
.collect([Link]());

Q54. Default methods in interfaces — diamond problem resolution.


✔ Answer:
interface A { default String greet() { return "Hello from A"; } }
interface B { default String greet() { return "Hello from B"; } }

// Class MUST override when two interfaces have same default method
class C implements A, B {
@Override
public String greet() {
return [Link](); // Explicitly choose A
}
}

// Static methods in interfaces (Java 8)


interface Validator {
static boolean isNotNull(Object o) { return o != null; }
}

Q55. [Link] (Java 12) — know the Java 8 workaround.


✔ Answer:
// Java 12+ teeing:
// [Link]<Double,Double> minMax = [Link]()
// .collect([Link](
// [Link]([Link](Employee::getSalary)),
// [Link]([Link](Employee::getSalary)),
// (min, max) -> [Link]([Link]().getSalary(), [Link]().getSalary())
// ));

// Java 8 workaround:
DoubleSummaryStatistics stats = [Link]()
.collect([Link](Employee::getSalary));
double min = [Link]();
double max = [Link]();

QUICK REFERENCE — Stream Terminal Operations

Method Return Type Use Case


collect() R Accumulate into Collection / Map / String
forEach() void Side effects per element
count() long Number of elements
findFirst() Optional<T> First element (ordered)
findAny() Optional<T> Any element (parallel-friendly)
min() / max() Optional<T> Extremes with Comparator
Java 8 Coding Interview Cheat Sheet | 7+ Years Experience Page 15
Method Return Type Use Case
reduce() T / Optional<T> Fold stream to single value
anyMatch() boolean Short-circuits on first true
allMatch() boolean Short-circuits on first false
noneMatch() boolean Short-circuits on first true
toArray() Object[] Convert to array

QUICK REFERENCE — Intermediate Stream Operations

Method Return Type Use Case

filter(Predicate) Stream<T> Keep matching elements


map(Function) Stream<R> Transform each element
flatMap(Function) Stream<R> Flatten nested streams
sorted(Comparator) Stream<T> Sort elements
distinct() Stream<T> Remove duplicates (uses equals)
limit(long) Stream<T> Take first N elements
skip(long) Stream<T> Skip first N elements
peek(Consumer) Stream<T> Debug / observe, pass-through
mapToInt/Long/Double IntStream... Specialized primitive streams

— End of Cheat Sheet —

55 coding questions covering Streams · Lambdas · Optional · Collectors · Parallel Streams · Date/Time · CompletableFuture

You might also like