Java 8
About
Java 8 introduced numerous significant features that changed the way Java developers write code.
1. Lambda Expressions
Lambda expressions provide a clear and concise way to represent anonymous functions. They eliminate the need for boilerplate code when implementing functional interfaces.
Example:
2. Functional Interfaces and @FunctionalInterface
Annotation
@FunctionalInterface
AnnotationA functional interface is an interface with exactly one abstract method, used as a type for lambda expressions.
Example:
3. Default and Static Methods in Interfaces
Interfaces can now contain default and static methods with implementations.
Example:
4. Streams API
The Streams API allows functional-style operations on collections.
Example:
5. Method References
Method references provide a shorthand notation for calling methods.
Example:
6. Optional Class
The Optional
class helps avoid NullPointerException
by wrapping values that may be null.
Example:
7. New Date and Time API (java.time
package)
java.time
package)Java 8 introduced a modern java.time
API to replace the legacy java.util.Date
and java.util.Calendar
.
Example:
8. Collectors in Streams
Collectors
are used to accumulate elements of a stream into a collection.
Example:
9. forEach()
Method in Iterable
forEach()
Method in IterableJava 8 introduced the forEach
method for Iterable
to iterate through collections.
Example:
10. computeIfAbsent()
and computeIfPresent()
in Map
computeIfAbsent()
and computeIfPresent()
in Map
Java 8 enhanced the Map
interface with new methods.
Example:
map.computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
If the specified key is not already associated with a value, this method computes a value using the given mapping function and inserts it into the map.
If the key is already present, it does nothing and returns the existing value.
Useful for lazy initialization of values in a map.
map.computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
If the specified key is already associated with a value, this method computes a new value using the given remapping function and updates the map.
If the function returns
null
, the key is removed from the map.If the key is not present, it does nothing.
Useful for modifying existing values in a map without checking for null manually.
11. String Joiner (java.util.StringJoiner
)
java.util.StringJoiner
)The StringJoiner
class is used for efficient string concatenation.
Example:
12. Base64 Encoding and Decoding
Java 8 introduced Base64
encoding and decoding.
Example:
13. Arrays.parallelSort()
Arrays.parallelSort()
Java 8 introduced parallelSort()
to sort arrays in parallel.
Example:
Last updated
Was this helpful?