Method Reference and Stream API in Java 8
Method Reference in Java 8
Method reference is used to refer to a method without calling it.
It is a short form of lambda expression.
It improves code readability and reusability.
The symbol '::' is used for method reference.
It does not execute the method directly; it only refers to it.
The method is executed when called through a functional interface or directly by name.
There are four types of method references:
1. Reference to a static method → ClassName::methodName
2. Reference to an instance method → object::methodName
3. Reference to an instance method of a class → ClassName::methodName
4. Reference to a constructor → ClassName::new
example
[Link]([Link]::println);
Stream API in Java 8
Stream API is used to process collections of data in a simple and efficient way.
It helps to perform operations like filtering, mapping, sorting, and reducing.
It supports functional-style programming on collections.
Stream does not store data; it processes data from sources like lists, arrays, etc.
Stream operations are of two types:
1. Intermediate operations (e.g., filter(), map(), sorted()) – return a new stream.
2. Terminal operations (e.g., forEach(), collect(), count()) – produce the final result.
Stream can be created from collections using the stream() method.
It makes code shorter, cleaner, and easier to read.
It allows processing data in parallel to improve performance.
common stream API
filter() – filters elements based on a condition.
map() – transforms elements.
forEach() – iterates through elements.
collect() – collects results into a list or set.
List<Integer> numbers = [Link](1, 2, 3, 4, 5);
[Link]()
.filter(n -> n % 2 == 0)
.forEach([Link]::println);