Java 8 cheat sheet: Essential features introduced in Java 8
1. Lambda Expressions
Lambda expressions provide a concise way to express instances of single-method interfaces (functional interfaces).
Syntax:
(parameters) -> expression
(parameters) -> { statements }
Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
numbers.forEach(n -> System.out.println(n));
2. Functional Interfaces
Functional interfaces have a single abstract method. Common examples in Java 8:
Runnable
Callable
Comparator
Custom functional interface:
@FunctionalInterface
Example:
@FunctionalInterface
interface MyFunction {
void execute();
}
3. Method References
Method references provide a shorthand notation for calling methods.
Syntax:
Class::staticMethod
object::instanceMethod
Class::instanceMethod
Example:
numbers.forEach(System.out::println); // Equivalent to n -> System.out.println(n)
4. Streams API
Streams allow processing sequences of elements in a functional style.
Common Operations:
filter
: Filters elements based on a condition.map
: Transforms elements.collect
: Collects results into a collection.
Example:
List<String> names = Arrays.asList("John", "Jane", "Doe");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J"))
.collect(Collectors.toList());
5. Default and Static Methods in Interfaces
Java 8 allows interfaces to have methods with a default implementation using the default
keyword.
Example:
interface MyInterface {
default void defaultMethod() {
System.out.println("Default method");
}
static void staticMethod() {
System.out.println("Static method");
}
}
6. Optional
The Optional
class is used to avoid null
checks.
Example:
Optional<String> optional = Optional.of("Hello"); optional.ifPresent(System.out::println); // Prints "Hello" if value is present
7. Date and Time API (java.time)
Java 8 introduced a new date and time API in the java.time
package.
Example:
LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); LocalDateTime dateTime = LocalDateTime.of(2023, 9, 7, 10, 0);
8. Collectors
The Collectors
class is used to accumulate elements of a stream into a collection or a single value.
Example:
List<String> names = Arrays.asList("John", "Jane", "Doe");
String result = names.stream()
.collect(Collectors.joining(", "));
System.out.println(result); // John, Jane, Doe
9. Stream Parallelism
Parallel streams enable parallel processing.
Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
numbers.parallelStream().forEach(System.out::println);
10. Predicate Interface
Used for filtering with a boolean condition.
Example:
Predicate<String> isEmpty = String::isEmpty;
System.out.println(isEmpty.test("")); // true
This cheat sheet provides a quick overview of key Java 8 features.
#Java8 #JavaDevelopment #SoftwareEngineering #LambdaExpressions #StreamAPI #JavaProgrammer #TechInnovation #CleanCode #FunctionalProgramming #CodingBestPractices #SoftwareArchitecture