Java Interview Questions Stream
Java Interview Questions Stream
8 Features
-Scribbles by Miss. Geetanjali Gajbhar
java.time Package – New Date & Time API (replaces Date and Calendar ).
Collectors API – Used to collect stream results (e.g., to list, set, map).
Syntax:
Basic Example:
Or simplified:
(a, b) -> a + b
Key Components:
Parameters: Like method parameters.
Works best with functional interfaces (interfaces with exactly one abstract
method).
@FunctionalInterface
interface MyOperation {
int operate(int a, int b);
}
Lambda Implementation:
Examples in Action:
1. Stream + Lambda:
When to Use:
With Streams, Collections, and Callbacks
Limitations:
Cannot use this to refer to lambda itself.
Abstract classes
Enums
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
System.out.println(grouped);
// Output: {3=[cat, dog], 5=[apple], 6=[banana], 8=[elephant]}
2. Function<T, R>
Method: R apply(T t)
3. Consumer<T>
Method: void accept(T t)
4. Supplier<T>
Method: T get()
5. BiPredicate<T, U>
Method: boolean test(T t, U u)
6. BiFunction<T, U, R>
Method: R apply(T t, U u)
7. BiConsumer<T, U>
Method: void accept(T t, U u)
1. Predicate<T> Practice
3. Consumer<T> Practice
4. Supplier<T> Practice
BiFunction<String, String, String> fullName = (first, last) -> first + " " + last;
System.out.println(fullName.apply("Geetanjali", "Gajbhar")); // Geetanjali Gajb
8. UnaryOperator<T> Practice
9. BinaryOperator<T> Practice
2. Write a lambda expression using Predicate<Integer> to filter out numbers that are
both even and divisible by 5 from a list.
2. Using BiPredicate<String, String> , check whether two email strings are equal ignoring
case.
3. Implement a Stream pipeline with map() , filter() , and collect() to return a list of
squared values of odd numbers.
3. Sort a list of Product objects by price using Comparator implemented with lambda.
2. Use Predicate<Employee> and .negate() to filter out employees younger than 30.
3. Write a method that accepts a Consumer<List<String>> and inside the lambda, sort
and print the list.
5. Use Stream and Lambda to print all even numbers from a list.
3. Filter a list of integers and print only prime numbers using Predicate and Stream .
4. Use a Map<String, Integer> of student names and marks. Use lambda to print
students scoring more than 75.
class Employee {
String name;
int age;
Employee(String name, int age) { this.name = name; this.age = age; }
}
compatibility).
2. default Method
Syntax:
Avoid breaking existing code when new methods are added to interfaces.
Example:
interface Vehicle {
default void start() {
System.out.println("Vehicle is starting...");
}
}
3. static Method
🔹 Syntax:
static return_type methodName() {
// implementation
}
Purpose:
Example:
interface Calculator {
static int add(int a, int b) {
return a + b;
}
}
interface A {
default void show() {
System.out.println("From A");
}
}
interface B {
default void show() {
System.out.println("From B");
}
}
5. Key Points
Feature default method static method
6. What will happen if a class does not override a conflicting default method?
Practice Examples
interface Printer {
default void print() {
System.out.println("Printing document...");
}
class C implements A, B {
public void show() {
A.super.show(); // or B.super.show()
}
}
1. Backward Compatibility
Before Java 8, adding a new method in an interface would break all
implementing classes.
Example:
interface OldInterface {
void existingMethod();
// void newMethod(); // ❌ Adding this breaks all implementing classes
}
→ Instead:
interface MathUtil {
static int square(int x) {
return x * x;
}
}
methods).
Summary:
Problem Before Java 8 Solution with Java 8
3. LocalDate Example
import java.time.LocalDate;
4. LocalTime Example
5. LocalDateTime Example
import java.time.LocalDateTime;
6. ZonedDateTime Example
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.LocalDate;
import java.time.Period;
import java.time.Duration;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
Feature Benefit
Using of()
Using empty()
5. Examples
orElse()
orElseGet()
orElseThrow()
ifPresent()
filter()
8. Interview-Tricky Questions
1. What's the difference between orElse() and orElseGet() ?
if (obj != null) {
obj.doSomething();
}
2. try-catch Block
try {
obj.doSomething();
} catch (NullPointerException e) {
System.out.println("Handled NPE");
4. Use Objects.requireNonNull()
Recommended Approach
Situation Best Practice
Final Answer:
2. Syntax:
ClassName::methodName
3. Instance Method
ClassName::instanceMethod First parameter becomes the caller
(Class)
Runnable r = Utility::greet;
r.run(); // Output: Hello!
class Printer {
public void print(String msg) {
System.out.println(msg);
}
}
// Using lambda:
// names.forEach(name -> System.out.println(name));
4. Constructor Reference
interface StudentCreator {
Student create();
}
class Student {
Student() {
System.out.println("Student object created");
}
}
StudentCreator sc = Student::new;
sc.create(); // Output: Student object created
list.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
7. Interview FAQs
Summary
Lambda Method Reference
import java.util.function.BiFunction;
import java.util.function.Consumer;
class Printer {
public void print(String msg) {
System.out.println(msg);
}
}
import java.util.Arrays;
import java.util.List;
4. Constructor Reference
import java.util.function.Supplier;
class Student {
Student() {
System.out.println("Student created!");
}
}
interface EmployeeFactory {
Employee create(String name, int age);
}
class Employee {
String name;
int age;
What is Nashorn?
Nashorn is a JavaScript engine introduced in Java 8 that allows you to run
JavaScript code inside Java applications.
Purpose of Nashorn:
Run JavaScript code from within Java (like embedded scripting).
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
Deprecation Note:
Nashorn was deprecated in Java 11 and removed in Java 15 due to lack of use
and better alternatives like GraalVM.
3. Stream vs Collection
Feature Collection Stream
4. Stream Creation
6. Examples
Map to square
Reduce to sum
map() forEach()
sorted() count()
limit() reduce()
1. From a list of Order objects, filter out orders that are delivered and cost > ₹1000.
4. Combine filter() , map() , and reduce() to calculate the sum of squares of even
numbers.
System.out.println(names);
1. What is Collectors ?
Collectors is a utility class in java.util.stream.Collectors that provides predefined methods
to collect the result of stream operations into various data structures.
3. Syntax:
stream.collect(Collectors.methodName());
Task
Top 50 Java 8 Coding Questions for Interviews (with Java 8 Features)
Lambda Expressions
3. Write a program using lambda to count strings starting with a given letter.
Functional Interfaces
6. Create your own functional interface and implement using lambda.
7. Use Predicate to check if a number is even.
8. Use Function to convert string to its length.
9. Use BiFunction to concatenate two strings.
10. Use Consumer to print strings in uppercase.
Method References
11. Use static method reference to print a message.
12. Use instance method reference from an object.
13. Use class method reference to print a list.
14. Use constructor reference to create object.
15. Use method reference inside stream forEach.