Best Practices and Design Patterns
import java.util.List; import java.util.function.Predicate; class Filter { public static <T> List<T> filter(List<T> items, Predicate<T> predicate) { return items.stream().filter(predicate).toList(); } } public class StrategyPatternExample { public static void main(String[] args) { List<String> names = List.of("Alice", "Bob", "Charlie", "David"); // Using lambda expression as a strategy List<String> filteredNames = Filter.filter(names, name -> name.length() > 4); System.out.println("Filtered Names: " + filteredNames); // Output: Filtered Names: [Alice, Charlie] } }interface Command { void execute(); } class Light { void turnOn() { System.out.println("Light is ON"); } void turnOff() { System.out.println("Light is OFF"); } } public class CommandPatternExample { public static void main(String[] args) { Light light = new Light(); // Using lambdas as commands Command turnOnCommand = light::turnOn; Command turnOffCommand = light::turnOff; // Invoking commands turnOnCommand.execute(); // Output: Light is ON turnOffCommand.execute(); // Output: Light is OFF } }
Last updated