Java 8+ Features : Practical Guide
Satyendra Pandey
Posted on November 26, 2024
Here’s a comprehensive set of practical exercises for all Java 8 features:
1. Lambda Expressions
Write a program that filters and prints even numbers from a list.
import java.util.Arrays;
import java.util.List;
public class LambdaExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
}
}
2. Method References
Write a program to reference a static method and an instance method.
import java.util.Arrays;
public class MethodReferenceExample {
public static void main(String[] args) {
String[] words = {"apple", "banana", "cherry"};
// Static method reference
Arrays.sort(words, String::compareToIgnoreCase);
System.out.println(String.join(", ", words));
// Instance method reference
Arrays.stream(words).forEach(System.out::println);
}
}
3. Functional Interfaces
Create a custom functional interface and use it with a lambda expression.
@FunctionalInterface
interface Greeting {
void sayHello(String name);
}
public class FunctionalInterfaceExample {
public static void main(String[] args) {
Greeting greeting = name -> System.out.println("Hello, " + name + "!");
greeting.sayHello("Alice");
}
}
4. Stream API
Write a program to find the sum of squares of odd numbers in a list.
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int sum = numbers.stream()
.filter(n -> n % 2 != 0)
.map(n -> n * n)
.reduce(0, Integer::sum);
System.out.println(sum);
}
}
5. Default Methods
Create an interface with a default method and override it in an implementing class.
interface Vehicle {
default void start() {
System.out.println("Vehicle is starting");
}
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car is starting");
}
}
public class DefaultMethodExample {
public static void main(String[] args) {
Vehicle car = new Car();
car.start();
}
}
6. Base64 Encode and Decode
Encode and decode a string using Base64.
import java.util.Base64;
public class Base64Example {
public static void main(String[] args) {
String original = "Java 8 Features";
// Encoding
String encoded = Base64.getEncoder().encodeToString(original.getBytes());
System.out.println("Encoded: " + encoded);
// Decoding
String decoded = new String(Base64.getDecoder().decode(encoded));
System.out.println("Decoded: " + decoded);
}
}
7. Static Methods in Interface
Create an interface with a static method.
interface Calculator {
static int add(int a, int b) {
return a + b;
}
}
public class StaticMethodInterfaceExample {
public static void main(String[] args) {
int sum = Calculator.add(5, 10);
System.out.println("Sum: " + sum);
}
}
8. Optional Class
Handle null
values safely using the Optional
class.
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
Optional<String> optional = Optional.ofNullable("Hello Optional");
optional.ifPresent(System.out::println);
System.out.println(optional.orElse("Default Value"));
}
}
9. Collectors Class
Group employees by department using Collectors.
import java.util.*;
import java.util.stream.Collectors;
class Employee {
String name;
String department;
Employee(String name, String department) {
this.name = name;
this.department = department;
}
public String getDepartment() {
return department;
}
public String toString() {
return name;
}
}
public class CollectorsExample {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Alice", "HR"),
new Employee("Bob", "IT"),
new Employee("Charlie", "HR"),
new Employee("Dave", "IT")
);
Map<String, List<Employee>> groupedByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
System.out.println(groupedByDept);
}
}
10. ForEach() Method
Iterate over a list using forEach
.
import java.util.Arrays;
public class ForEachExample {
public static void main(String[] args) {
Arrays.asList("A", "B", "C").forEach(System.out::println);
}
}
11. Parallel Array Sorting
Sort an array in parallel.
import java.util.Arrays;
public class ParallelSortExample {
public static void main(String[] args) {
int[] numbers = {5, 3, 2, 8, 1};
Arrays.parallelSort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
12. Nashorn JavaScript Engine
Execute JavaScript code within Java.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class NashornExample {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("print('Hello from JavaScript');");
}
}
13. Type and Repeating Annotations
Create a custom annotation and apply it multiple times.
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Repeatable(Authors.class)
@interface Author {
String name();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Authors {
Author[] value();
}
@Author(name = "Author1")
@Author(name = "Author2")
class Book {}
public class AnnotationExample {
public static void main(String[] args) {
Author[] authors = Book.class.getAnnotationsByType(Author.class);
for (Author author : authors) {
System.out.println(author.name());
}
}
}
14. IO Enhancements
Read all lines from a file.
import java.nio.file.*;
import java.io.IOException;
public class IOEnhancementsExample {
public static void main(String[] args) throws IOException {
Path file = Paths.get("test.txt");
Files.write(file, "Java IO Enhancements".getBytes());
Files.lines(file).forEach(System.out::println);
}
}
15. Concurrency Enhancements
Use the CompletableFuture
API.
import java.util.concurrent.CompletableFuture;
public class ConcurrencyExample {
public static void main(String[] args) {
CompletableFuture.runAsync(() -> System.out.println("Running async task"))
.thenRun(() -> System.out.println("Task completed"))
.join();
}
}
16. JDBC Enhancements
Fetch database metadata using JDBC.
import java.sql.*;
public class JDBCEEnhancementsExample {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("Database Product Name: " + metaData.getDatabaseProductName());
}
}
Let me know if you'd like further details or advanced exercises for any specific topic!
Posted on November 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.