Navigation: Main Tutorial Index | Practice Programs | Previous: Collections | Next: Multithreading
Java 8 was released in March 2014. It introduced several important features that changed how developers write Java applications.
Before Java 8, developers commonly used anonymous inner classes and traditional loops to perform operations.
Java 8 introduced functional programming capabilities that allow developers to write cleaner and more expressive code.
- Lambda Expressions
- Functional Interfaces
- Built-in Functional Interfaces
- Method References
- Stream API
- Optional Class
- Default Methods in Interfaces
- Static Methods in Interfaces
- New Date and Time API
- forEach() Method
- Collectors
- Parallel Streams
Consider the following example.
Before Java 8:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList(
"Ayush", "Rahul", "Amit"
);
for (String name : names) {
System.out.println(name);
}
}
}Using Java 8:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList(
"Ayush", "Rahul", "Amit"
);
names.forEach(name -> System.out.println(name));
}
}Both programs produce:
Ayush
Rahul
Amit
The Java 8 version uses a Lambda Expression to make the code more concise.
A Lambda Expression is a short way to represent an anonymous function.
It allows us to pass behavior as an argument to a method.
Lambda Expressions are mainly used with Functional Interfaces.
(parameters) -> expressionOr:
(parameters) -> {
// Multiple statements
};No parameters:
() -> System.out.println("Hello Java 8");One parameter:
name -> System.out.println(name);Multiple parameters:
(a, b) -> a + b;public class Main {
public static void main(String[] args) {
Runnable task = () -> {
System.out.println("Java 8 Lambda Expression");
};
task.run();
}
}Output:
Java 8 Lambda Expression
interface Greeting {
void sayHello(String name);
}
public class Main {
public static void main(String[] args) {
Greeting greeting =
name -> System.out.println("Hello " + name);
greeting.sayHello("Ayush");
}
}Output:
Hello Ayush
interface Calculator {
int add(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator calculator = (a, b) -> a + b;
System.out.println(calculator.add(10, 20));
}
}Output:
30
interface Calculator {
int calculate(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator calculator = (a, b) -> {
int sum = a + b;
System.out.println("Calculating...");
return sum;
};
System.out.println("Result: " +
calculator.calculate(10, 20));
}
}Output:
Calculating...
Result: 30
- Reduces boilerplate code.
- Improves readability.
- Supports functional programming.
- Makes collection processing easier.
- Works naturally with Stream API.
- Reduces the need for anonymous inner classes in many situations.
A Functional Interface is an interface that contains exactly one abstract method.
It is also known as a Single Abstract Method (SAM) interface.
Functional Interfaces can contain:
- One abstract method.
- Multiple default methods.
- Multiple static methods.
- Methods inherited from Object do not count as additional abstract methods for this purpose.
@FunctionalInterface
interface MyInterface {
void display();
}The @FunctionalInterface annotation is optional, but recommended because the compiler checks that the interface follows the functional-interface rules.
@FunctionalInterface
interface Message {
void showMessage();
}
public class Main {
public static void main(String[] args) {
Message message = () ->
System.out.println("Welcome to Java 8");
message.showMessage();
}
}Output:
Welcome to Java 8
@FunctionalInterface
interface Message {
void display();
}
public class Main {
public static void main(String[] args) {
Message message = new Message() {
public void display() {
System.out.println("Traditional Implementation");
}
};
message.display();
}
}@FunctionalInterface
interface Message {
void display();
}
public class Main {
public static void main(String[] args) {
Message message =
() -> System.out.println("Lambda Implementation");
message.display();
}
}Output:
Lambda Implementation
Java 8 provides several built-in Functional Interfaces in the java.util.function package.
| Interface | Abstract Method | Purpose |
|---|---|---|
| Predicate | test() | Tests a condition |
| Function<T,R> | apply() | Converts one value into another |
| Consumer | accept() | Consumes a value |
| Supplier | get() | Supplies a value |
| UnaryOperator | apply() | Takes and returns the same type |
| BinaryOperator | apply() | Takes two values of the same type and returns that type |
Predicate is a Functional Interface used to test a condition.
It accepts one argument and returns a boolean value.
Predicate<T>Abstract method:
boolean test(T value);import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<Integer> isEven =
number -> number % 2 == 0;
System.out.println(isEven.test(10));
System.out.println(isEven.test(15));
}
}Output:
true
false
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<String> checkLength =
name -> name.length() > 5;
System.out.println(checkLength.test("Ayush"));
System.out.println(checkLength.test("RahulSharma"));
}
}Output:
false
true
Predicate provides useful methods:
and()or()negate()
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<Integer> greaterThanTen =
number -> number > 10;
Predicate<Integer> even =
number -> number % 2 == 0;
Predicate<Integer> result =
greaterThanTen.and(even);
System.out.println(result.test(20));
System.out.println(result.test(15));
}
}Output:
true
false
Function is used to transform one value into another.
It accepts one input and returns one output.
Function<T, R>Abstract method:
R apply(T value);import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, String> convert =
name -> name.toUpperCase();
System.out.println(convert.apply("ayush"));
}
}Output:
AYUSH
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<Integer, Integer> square =
number -> number * number;
System.out.println(square.apply(5));
}
}Output:
25
Function provides andThen() and compose().
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<Integer, Integer> multiply =
number -> number * 2;
Function<Integer, Integer> add =
number -> number + 10;
Function<Integer, Integer> result =
multiply.andThen(add);
System.out.println(result.apply(5));
}
}Output:
20
Explanation:
- Input = 5.
- Multiply by 2 = 10.
- Add 10 = 20.
andThen() executes the current Function first and the next Function afterward.
compose() executes the supplied Function first and the current Function afterward.
Consumer accepts an argument but does not return a result.
Consumer<T>Abstract method:
void accept(T value);import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<String> print =
name -> System.out.println("Hello " + name);
print.accept("Ayush");
}
}Output:
Hello Ayush
import java.util.ArrayList;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ayush");
names.add("Rahul");
names.add("Amit");
Consumer<String> display =
name -> System.out.println(name);
names.forEach(display);
}
}Output:
Ayush
Rahul
Amit
Supplier does not accept an argument but returns a value.
Supplier<T>Abstract method:
T get();import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier<String> message =
() -> "Welcome to Java Programming";
System.out.println(message.get());
}
}Output:
Welcome to Java Programming
import java.util.Random;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Random random = new Random();
Supplier<Integer> generate =
() -> random.nextInt(100) + 1;
System.out.println(generate.get());
}
}Output:
A random number between 1 and 100
The actual output changes on each execution.
| Interface | Input | Output | Method |
|---|---|---|---|
| Predicate | One | boolean | test() |
| Function<T,R> | One | R | apply() |
| Consumer | One | void | accept() |
| Supplier | None | T | get() |
Method References are a shorthand for Lambda Expressions when an existing method already performs the required operation.
They use the :: operator.
ClassName::methodName- Reference to a static method.
- Reference to an instance method of a particular object.
- Reference to an instance method of an arbitrary object of a particular type.
- Reference to a constructor.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void print(String name) {
System.out.println(name);
}
public static void main(String[] args) {
List<String> names =
Arrays.asList("Ayush", "Rahul", "Amit");
names.forEach(Main::print);
}
}Output:
Ayush
Rahul
Amit
import java.util.Arrays;
import java.util.List;
public class Main {
public void display(String name) {
System.out.println("Hello " + name);
}
public static void main(String[] args) {
Main obj = new Main();
List<String> names =
Arrays.asList("Ayush", "Rahul");
names.forEach(obj::display);
}
}Output:
Hello Ayush
Hello Rahul
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names =
Arrays.asList("ayush", "rahul", "amit");
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}Output:
AYUSH
RAHUL
AMIT
import java.util.function.Supplier;
class Student {
Student() {
System.out.println("Student Object Created");
}
}
public class Main {
public static void main(String[] args) {
Supplier<Student> student =
Student::new;
student.get();
}
}Output:
Student Object Created
Stream API is one of the most important Java 8 features.
It allows developers to process collections of data in a declarative way.
A Stream represents a sequence of elements that can be processed through operations such as filtering, mapping, sorting, and reducing.
Before Java 8:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(15);
numbers.add(20);
numbers.add(25);
numbers.add(30);
for (Integer number : numbers) {
if (number % 2 == 0) {
System.out.println(number);
}
}
}
}Using Stream API:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 15, 20, 25, 30);
numbers.stream()
.filter(number -> number % 2 == 0)
.forEach(System.out::println);
}
}Output:
10
20
30
- A Stream does not store data.
- It processes data from a source such as a collection or array.
- It supports functional-style operations.
- Stream operations do not normally modify the original source.
- Intermediate operations are lazy.
- A Stream cannot be reused after a terminal operation.
- Streams can be sequential or parallel.
Collection
|
v
Source Stream
|
v
Intermediate Operations
|
+---- filter()
|
+---- map()
|
+---- sorted()
|
v
Terminal Operation
|
+---- collect()
|
+---- forEach()
|
+---- count()
|
v
Result
Intermediate operations return another Stream.
They are lazy and execute when a terminal operation is invoked.
Filters elements based on a condition.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 15, 20, 25, 30);
numbers.stream()
.filter(number -> number > 20)
.forEach(System.out::println);
}
}Output:
25
30
Transforms each element into another value.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names =
Arrays.asList("ayush", "rahul", "amit");
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}Output:
AYUSH
RAHUL
AMIT
Sorts the elements.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(50, 10, 40, 20, 30);
numbers.stream()
.sorted()
.forEach(System.out::println);
}
}Output:
10
20
30
40
50
numbers.stream()
.sorted((a, b) -> b.compareTo(a))
.forEach(System.out::println);Output:
50
40
30
20
10
Removes duplicate elements.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 20, 10, 30, 20);
numbers.stream()
.distinct()
.forEach(System.out::println);
}
}Output:
10
20
30
Limits the number of elements.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 20, 30, 40, 50);
numbers.stream()
.limit(3)
.forEach(System.out::println);
}
}Output:
10
20
30
Skips the first specified number of elements.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 20, 30, 40, 50);
numbers.stream()
.skip(2)
.forEach(System.out::println);
}
}Output:
30
40
50
Transforms each element into a Stream and combines the resulting Streams into one Stream.
It is useful for processing nested collections.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<List<Integer>> numbers = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6)
);
numbers.stream()
.flatMap(list -> list.stream())
.forEach(System.out::println);
}
}Output:
1
2
3
4
5
6
Terminal operations produce a result or side effect and consume the Stream.
Performs an action for every element.
numbers.stream()
.forEach(System.out::println);Returns the number of elements.
long count = numbers.stream()
.filter(n -> n > 20)
.count();
System.out.println(count);Collects the elements into a collection or another result container.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 15, 20, 25, 30);
List<Integer> evenNumbers =
numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
}
}Output:
[10, 20, 30]
Combines Stream elements into a single result.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 20, 30, 40);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println("Sum: " + sum);
}
}Output:
Sum: 100
Finds the minimum and maximum values.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(50, 10, 40, 20, 30);
int min = numbers.stream()
.min(Integer::compareTo)
.get();
int max = numbers.stream()
.max(Integer::compareTo)
.get();
System.out.println("Minimum: " + min);
System.out.println("Maximum: " + max);
}
}Output:
Minimum: 10
Maximum: 50
In production code, consider handling an empty Stream using Optional instead of calling get() without checking.
These operations test conditions and return boolean values.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 20, 30, 40);
System.out.println(
numbers.stream().anyMatch(n -> n > 30)
);
System.out.println(
numbers.stream().allMatch(n -> n > 0)
);
System.out.println(
numbers.stream().noneMatch(n -> n < 0)
);
}
}Output:
true
true
true
Collectors are utility methods used with Stream's collect() operation.
They are available in the java.util.stream.Collectors class.
| Method | Purpose |
|---|---|
| toList() | Collects elements into a List |
| toSet() | Collects elements into a Set |
| toMap() | Collects elements into a Map |
| joining() | Joins strings |
| counting() | Counts elements |
| groupingBy() | Groups elements by a classifier |
| partitioningBy() | Splits elements into true and false groups |
| averagingInt() | Calculates an average |
| summingInt() | Calculates a sum |
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> names =
Arrays.asList("Ayush", "Rahul", "Amit");
String result = names.stream()
.collect(Collectors.joining(", "));
System.out.println(result);
}
}Output:
Ayush, Rahul, Amit
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> names =
Arrays.asList("Amit", "Ayush", "Ankit",
"Rahul", "Rohit");
Map<Character, List<String>> grouped =
names.stream()
.collect(Collectors.groupingBy(
name -> name.charAt(0)
));
System.out.println(grouped);
}
}Possible Output:
{A=[Amit, Ayush, Ankit], R=[Rahul, Rohit]}
The order of map entries is not guaranteed by the default groupingBy collector.
Partitions elements into two groups based on a boolean condition.
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 15, 20, 25, 30);
Map<Boolean, List<Integer>> result =
numbers.stream()
.collect(Collectors.partitioningBy(
n -> n % 2 == 0
));
System.out.println(result);
}
}Output:
{false=[15, 25], true=[10, 20, 30]}
Optional is a container object that may or may not contain a non-null value.
It helps developers represent the absence of a value and reduce accidental NullPointerException.
public class Main {
public static void main(String[] args) {
String name = null;
if (name != null) {
System.out.println(name.length());
} else {
System.out.println("Name is not available");
}
}
}Output:
Name is not available
Optional<String> value1 = Optional.of("Ayush");
Optional<String> value2 = Optional.empty();
Optional<String> value3 = Optional.ofNullable(null);Important methods:
| Method | Description |
|---|---|
| of() | Creates Optional with a non-null value |
| empty() | Creates an empty Optional |
| ofNullable() | Accepts a nullable value |
| isPresent() | Checks whether a value exists |
| ifPresent() | Performs an action if a value exists |
| orElse() | Returns a default value if empty |
| orElseGet() | Gets a fallback value from a Supplier if empty |
| orElseThrow() | Throws an exception if empty |
| get() | Retrieves the value; throws if empty |
| map() | Transforms the contained value |
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name =
Optional.ofNullable(null);
System.out.println(
name.orElse("Unknown")
);
}
}Output:
Unknown
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name =
Optional.of("Ayush");
name.ifPresent(value ->
System.out.println("Name: " + value)
);
}
}Output:
Name: Ayush
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name =
Optional.of("ayush");
Optional<String> result =
name.map(String::toUpperCase);
System.out.println(result.orElse("Unknown"));
}
}Output:
AYUSH
Important: Optional.get() should not be called without checking whether a value is present. Optional is primarily intended for return types where a result may be absent, not as a replacement for every nullable field or variable.
Java 8 introduced default methods in interfaces.
A default method is an interface method with an implementation.
It allows developers to add new behavior to an existing interface without forcing every existing implementation class to implement the new method.
default void methodName() {
// Implementation
}interface Vehicle {
void start();
default void stop() {
System.out.println("Vehicle Stopped");
}
}
class Car implements Vehicle {
public void start() {
System.out.println("Car Started");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start();
car.stop();
}
}Output:
Car Started
Vehicle Stopped
If a class implements two interfaces that provide conflicting default methods with the same signature, the class must resolve the conflict by overriding the method.
interface A {
default void display() {
System.out.println("Interface A");
}
}
interface B {
default void display() {
System.out.println("Interface B");
}
}
class Test implements A, B {
public void display() {
A.super.display();
B.super.display();
}
}
public class Main {
public static void main(String[] args) {
Test obj = new Test();
obj.display();
}
}Output:
Interface A
Interface B
Java 8 allows interfaces to contain static methods with implementations.
They are called using the interface name.
interface Calculator {
static int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
int result = Calculator.add(10, 20);
System.out.println(result);
}
}Output:
30
Important: Interface static methods are not inherited as instance methods by implementing classes.
Before Java 8, developers commonly used Date and Calendar.
These older APIs had usability problems, including mutable date objects and confusing month handling.
Java 8 introduced the java.time package.
| Class | Purpose |
|---|---|
| LocalDate | Represents a date |
| LocalTime | Represents a time |
| LocalDateTime | Represents date and time |
| ZonedDateTime | Represents date and time with a time zone |
| Instant | Represents a point on the UTC timeline |
| Period | Represents a date-based amount of time |
| Duration | Represents a time-based amount of time |
| DateTimeFormatter | Formats and parses dates and times |
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println(date);
}
}Output:
The current date in YYYY-MM-DD format
The actual date depends on the system clock.
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date =
LocalDate.of(2026, 11, 21);
System.out.println(date);
}
}Output:
2026-11-21
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println(time);
}
}Output:
The current local time
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime dateTime =
LocalDateTime.now();
System.out.println(dateTime);
}
}import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate today =
LocalDate.of(2026, 11, 21);
System.out.println(today.plusDays(5));
System.out.println(today.minusDays(5));
System.out.println(today.plusMonths(2));
System.out.println(today.plusYears(1));
}
}Output:
2026-11-26
2026-11-16
2027-01-21
2027-11-21
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDate date =
LocalDate.of(2026, 11, 21);
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("dd-MM-yyyy");
System.out.println(date.format(formatter));
}
}Output:
21-11-2026
Period measures date-based differences in years, months, and days.
import java.time.LocalDate;
import java.time.Period;
public class Main {
public static void main(String[] args) {
LocalDate start =
LocalDate.of(2020, 1, 1);
LocalDate end =
LocalDate.of(2025, 1, 1);
Period period =
Period.between(start, end);
System.out.println(period.getYears());
}
}Output:
5
Duration measures time-based differences.
import java.time.Duration;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime start =
LocalTime.of(10, 0);
LocalTime end =
LocalTime.of(12, 30);
Duration duration =
Duration.between(start, end);
System.out.println(duration.toMinutes());
}
}Output:
150
Parallel Streams allow processing of Stream elements using multiple threads.
They use the common ForkJoinPool by default.
numbers.stream()
.forEach(System.out::println);numbers.parallelStream()
.forEach(System.out::println);import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum);
}
}Output:
Sum: 15
- Can improve performance for suitable workloads.
- Allows parallel processing.
- Reduces the need to manually manage threads for many data-processing tasks.
- Parallel execution has overhead.
- Small datasets may perform worse.
- Shared mutable state can cause race conditions.
- Encounter order is not always preserved by terminal operations such as
forEach(). - Blocking operations may reduce performance.
Important: Parallel Streams are not automatically faster. Benchmark with realistic data before using them in production.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 15, 20, 25, 30);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum of even numbers: " + sum);
}
}Output:
Sum of even numbers: 60
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
}
public class Main {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Ayush", 85),
new Student("Rahul", 35),
new Student("Amit", 75),
new Student("Rohit", 25)
);
List<String> passed = students.stream()
.filter(student -> student.marks >= 40)
.map(student -> student.name)
.collect(Collectors.toList());
System.out.println(passed);
}
}Output:
[Ayush, Amit]
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
}
public class Main {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Ayush", 85),
new Student("Rahul", 90),
new Student("Amit", 78)
);
Optional<Student> topper =
students.stream()
.max((s1, s2) ->
Integer.compare(s1.marks, s2.marks));
topper.ifPresent(student ->
System.out.println(
student.name + " - " + student.marks
)
);
}
}Output:
Rahul - 90
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class Employee {
String name;
double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
}
public class Main {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Ayush", 45000),
new Employee("Rahul", 60000),
new Employee("Amit", 35000)
);
employees.stream()
.sorted(Comparator.comparingDouble(
employee -> employee.salary
))
.forEach(employee ->
System.out.println(
employee.name + " - " + employee.salary
)
);
}
}Output:
Amit - 35000.0
Ayush - 45000.0
Rahul - 60000.0
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String sentence =
"java is easy and java is powerful";
Map<String, Long> frequency =
Arrays.stream(sentence.split("\\s+"))
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
System.out.println(frequency);
}
}Possible Output:
{java=2, is=2, easy=1, and=1, powerful=1}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> names =
Arrays.asList("ayush", "rahul", "amit");
List<String> result =
names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result);
}
}Output:
[AYUSH, RAHUL, AMIT]
- Thinking every interface is a Functional Interface.
- Writing a Lambda Expression without understanding the target Functional Interface.
- Trying to reuse a Stream after a terminal operation.
- Modifying a collection while processing its Stream.
- Confusing map() with flatMap().
- Using Optional.get() without checking whether a value exists.
- Assuming parallelStream() is always faster.
- Using side effects in Stream pipelines unnecessarily.
- Confusing Predicate with Function.
- Confusing Consumer with Supplier.
- Assuming intermediate Stream operations execute immediately.
- Using mutable shared state inside parallel Stream operations.
- Confusing LocalDate with LocalDateTime.
- Assuming a Stream changes the original collection.
- Use Lambda Expressions when they make code easier to understand.
- Use
@FunctionalInterfacefor custom single-abstract-method interfaces. - Prefer built-in Functional Interfaces when suitable.
- Use Method References when they make a Lambda Expression clearer.
- Use Streams for declarative data processing.
- Avoid unnecessarily long Stream pipelines.
- Prefer Optional return types when a method may have no result.
- Use
java.timeclasses instead of legacy Date and Calendar for new date-time code. - Use sequential Streams by default unless parallel processing has a clear benefit.
- Avoid modifying external state inside Stream operations.
- Use
orElseGet()when fallback creation should be lazy. - Remember that Streams are single-use.
- What is Java 8?
Answer: Java 8 is a Java release that added lambda expressions and functional interfaces plus Streams, Optional, default methods, and the java.time API.
- What are the major features introduced in Java 8?
Answer: Major features include lambdas, functional interfaces, built-in function types, method references, Streams, Optional, interface default/static methods, and the new Date/Time API.
- What is a Lambda Expression?
Answer: A lambda expression is a concise implementation of a functional interface method, written as parameters, ->, and a body.
- What is the syntax of a Lambda Expression?
Answer: The syntax is (parameters) -> expression or (parameters) -> { statements; }; parameter types are often inferred.
- What is a Functional Interface?
Answer: A functional interface has exactly one abstract method, although it may also declare default or static methods.
- What is a SAM interface?
Answer: SAM means Single Abstract Method: an interface with one abstract method that can therefore be implemented by a lambda.
- What is the purpose of @FunctionalInterface?
Answer: @FunctionalInterface documents intent and makes compilation fail if the interface has no or more than one abstract method.
- What is the difference between an anonymous inner class and a Lambda Expression?
Answer: A lambda is a functional-interface implementation without an ordinary inner-class instance; an anonymous class creates a separate class instance and can hold fields.
- What is a Predicate?
Answer: Predicate<T> represents a boolean test through test(T).
- What is a Consumer?
Answer: Consumer<T> represents an action that accepts a value and returns no result through accept(T).
- What is a Supplier?
Answer: Supplier<T> supplies a value without input through get().
- What is a Function?
Answer: Function<T,R> transforms an input of type T into a result of type R through apply(T).
- What is the difference between Predicate and Function?
Answer: Predicate returns boolean and is used for filtering or testing; Function returns a value and is used for transformation.
- What is a Method Reference?
Answer: A method reference uses :: as shorthand for a lambda that invokes an existing method.
- What are the types of Method References?
Answer: The forms are static methods, an instance method on a specific object, an instance method on an arbitrary object of a type, and constructors.
- What is the Stream API?
Answer: The Stream API provides lazy, functional-style pipelines for processing sequences from collections, arrays, or generators.
- What is the difference between a Collection and a Stream?
Answer: A Collection stores data and is reusable; a Stream processes a source and cannot normally be reused after a terminal operation.
- What are intermediate and terminal operations?
Answer: Intermediate operations return streams and are lazy; terminal operations consume the pipeline and produce a result or side effect.
- What is the difference between map() and flatMap()?
Answer: map() performs a one-to-one transformation; flatMap() transforms each element to a stream and flattens all results.
- What is the difference between filter() and map()?
Answer: filter() removes elements that fail a predicate; map() transforms each element.
- What is the purpose of reduce()?
Answer: reduce() combines stream elements into one result using an accumulator operation.
- What is the difference between findFirst() and findAny()?
Answer: findFirst() returns the first element in encounter order; findAny() may return any element and is more flexible for parallel streams.
- What is Optional?
Answer: Optional<T> is a container that may hold a value, allowing absence to be represented without accidental null dereferences.
- What is the difference between orElse() and orElseGet()?
Answer: orElse() takes a ready value and evaluates eagerly; orElseGet() invokes a supplier only when the Optional is empty.
- What are default methods in interfaces?
Answer: Default methods provide interface implementations so libraries can evolve without breaking existing implementations.
- What are static methods in interfaces?
Answer: Static interface methods belong to the interface and are called through the interface name, not implementation instances.
- Why were default methods introduced in Java 8?
Answer: Default methods support backward-compatible evolution of interfaces and shared behavior across implementations.
- What happens when two interfaces have the same default method?
Answer: A class with conflicting inherited defaults must override the method explicitly or declare the abstract override to resolve the ambiguity.
- What is a parallel Stream?
Answer: A parallel stream partitions work and executes it concurrently, usually using the Fork/Join common pool.
- What is the difference between sequential and parallel Streams?
Answer: A sequential stream processes elements serially; a parallel stream may speed suitable workloads but adds synchronization and task overhead.
- What is lazy evaluation in Stream API?
Answer: Lazy evaluation defers intermediate stream processing until a terminal operation starts, allowing operations to be fused.
- What is the difference between forEach() and forEachOrdered()?
Answer: forEach() is terminal and does not guarantee encounter order for parallel streams; forEachOrdered() does preserve encounter order.
- What is the purpose of Collectors.groupingBy()?
Answer: Collectors.groupingBy() collects elements into a map whose keys are classifier results.
- What is the difference between groupingBy() and partitioningBy()?
Answer: groupingBy() creates groups for each key; partitioningBy() creates exactly true/false buckets using a predicate.
- What is the Java 8 Date and Time API?
Answer: The Java 8 Date/Time API is the immutable, thread-safe java.time package for dates, times, durations, periods, and formatting.
- What is the difference between LocalDate and LocalDateTime?
Answer: LocalDate contains only a date; LocalDateTime contains both date and time without a zone.
- What is the difference between Period and Duration?
Answer: Period represents date-based calendar differences; Duration represents a machine-oriented time difference in seconds and nanoseconds.
- What is a method reference to a constructor?
Answer: A constructor reference has the form ClassName::new and implements a functional interface that creates a new instance.
- What is Function chaining?
Answer: Function chaining passes one function’s result into the next, using andThen() or compose().
- Can a Functional Interface contain default and static methods?
Answer: Yes; default and static methods are allowed because the functional-interface rule counts only abstract methods.
Important: This section contains questions only. Try to solve each exercise independently before checking any external solution.
Completed solutions are available in the Practice-Programs folder.
- Write a Lambda Expression to print "Hello Java 8".
- Write a Lambda Expression to add two integers.
- Create a Functional Interface to calculate the square of a number.
- Use Predicate to check whether a number is even.
- Use Predicate to check whether a string starts with the letter A.
- Use Function to convert a String into uppercase.
- Use Function to calculate the square of an integer.
- Use Consumer to print student names.
- Use Supplier to generate a welcome message.
- Use a Method Reference to print elements of an ArrayList.
- Use Stream API to filter even numbers from a list.
- Use Stream API to find numbers greater than 50.
- Use map() to convert a list of strings into uppercase.
- Use sorted() to sort a list of integers in ascending order.
- Use sorted() to sort a list of integers in descending order.
- Use distinct() to remove duplicate elements.
- Use limit() to retrieve the first five elements.
- Use skip() to skip the first three elements.
- Use reduce() to calculate the sum of all numbers.
- Use count() to count strings having more than five characters.
- Use flatMap() to flatten a list of lists.
- Use Optional to handle a nullable String.
- Use DateTimeFormatter to display a date in dd-MM-yyyy format.
- Use groupingBy() to group names based on their first character.
- Use partitioningBy() to separate even and odd numbers.
- Create a Student class and use Stream API to find students who passed.
- Find the student with the highest marks using Stream API.
- Sort employees by salary using Comparator and Stream API.
- Calculate the average salary of employees using Collectors.
- Group employees according to their departments.
- Create a word-frequency counter using groupingBy() and counting().
- Use Function chaining to perform multiple transformations.
- Create a custom Functional Interface and implement it using Lambda.
- Implement a default method in an interface.
- Implement a static method in an interface.
- Create a program demonstrating conflict resolution between two interface default methods.
- Calculate the difference between two dates using Period.
- Calculate the duration between two times using Duration.
- Compare sequential and parallel Stream processing on a sufficiently large dataset.
- Build a student management program using ArrayList, Lambda Expressions, Streams, and Optional.
In this chapter, you learned:
- Introduction to Java 8.
- Lambda Expressions.
- Functional Interfaces.
- Predicate, Function, Consumer, and Supplier.
- Method References.
- Stream API.
- Intermediate and terminal operations.
- Collectors.
- Optional Class.
- Default and Static Methods in Interfaces.
- New Date and Time API.
- Parallel Streams.
- Practical Java 8 programs.
- Interview questions and exercises.
| Feature | Main Purpose |
|---|---|
| Lambda Expression | Write concise anonymous functions |
| Functional Interface | Define a single abstract operation |
| Predicate | Test a condition |
| Function | Transform data |
| Consumer | Consume data |
| Supplier | Supply data |
| Method Reference | Refer to an existing method |
| Stream API | Process sequences of data |
| Optional | Represent a possibly absent value |
| Collectors | Collect and group Stream results |
| Date and Time API | Handle dates and times |
| Parallel Stream | Process data in parallel |
Java 8 is essential for modern Java development. Lambda Expressions, Functional Interfaces, and Stream API are frequently used in enterprise applications, Spring Boot projects, interviews, and competitive programming.
Practice each program yourself and understand how the data flows through each operation.
Topics covered in the next chapter:
- Introduction to Multithreading.
- Process vs Thread.
- Thread Life Cycle.
- Creating Threads using Thread Class.
- Creating Threads using Runnable Interface.
- Thread Methods.
- Thread Priority.
- Sleep, Join, and Yield.
- Synchronization.
- Race Conditions.
- Deadlock.
- Inter-thread Communication.
- wait(), notify(), and notifyAll().
- Executor Framework.
- Callable and Future.
- Concurrent Collections.
- Practical Multithreading Programs.
- Interview Questions and Practice Exercises.
Keep learning, keep coding, and build strong Java fundamentals one chapter at a time.