Java Snippets
Modern Java programming patterns and features
Stream API
javaModern Java Stream operations
import java.util.List;
import java.util.stream.Collectors;
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
// Filter and map
List<Integer> evenSquares = numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
// Reduce
int sum = numbers.stream()
.reduce(0, Integer::sum);
// Group by
Map<Boolean, List<Integer>> evenOddGroups = numbers.stream()
.collect(Collectors.groupingBy(n -> n % 2 == 0));Optional Class
javaNull safety with Optional
import java.util.Optional;
class UserService {
public Optional<User> findById(String id) {
// Simulated database lookup
User user = database.find(id);
return Optional.ofNullable(user);
}
}
// Usage
UserService service = new UserService();
// Safe chaining
String username = service.findById("123")
.map(User::getName)
.orElse("Anonymous");
// With multiple operations
service.findById("123")
.filter(user -> user.getAge() > 18)
.ifPresent(user -> sendEmail(user));Generics
javaGeneric classes and methods
// Generic class
public class Box<T> {
private T content;
public Box(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
// Generic method
public <T extends Comparable<T>> T findMax(List<T> list) {
if (list.isEmpty()) {
throw new IllegalArgumentException("Empty list");
}
T max = list.get(0);
for (T item : list) {
if (item.compareTo(max) > 0) {
max = item;
}
}
return max;
}CompletableFuture
javaAsynchronous programming in Java
import java.util.concurrent.CompletableFuture;
public class AsyncService {
public CompletableFuture<String> fetchData() {
return CompletableFuture.supplyAsync(() -> {
// Simulate async operation
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Data";
});
}
// Chaining operations
public void processData() {
fetchData()
.thenApply(data -> data.toUpperCase())
.thenAccept(System.out::println)
.exceptionally(error -> {
System.err.println("Error: " + error);
return null;
});
}
}