### Create and Start a Basic Thread Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/concurrent-module.md Demonstrates how to create a new thread using a lambda expression and start its execution. The thread prints its name to the console. ```java Thread t = new Thread(() -> { System.out.println("Running in thread: " + Thread.currentThread().getName()); }); t.start(); // Start thread execution ``` -------------------------------- ### User Object Initialization Example Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/optional-module.md Demonstrates how to create and populate a User object, including setting an Optional Address. ```java User user = new User(); user.setUsername("biezhi"); user.setPassword("secret123"); user.setAge(30); user.setOptAddress(Optional.of(new Address("Darwin Rd", "88"))); ``` -------------------------------- ### Address Object Initialization Examples Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/optional-module.md Shows different ways to instantiate an Address object using its constructors and setters. ```java // No-arg constructor Address addr1 = new Address(); // All-args constructor Address addr2 = new Address("Darwin Rd", "88"); // Builder-style with setters Address addr3 = new Address(); addr3.setStreet("Darwin Rd"); addr3.setDoor("88"); ``` -------------------------------- ### Address Constructor Usage Examples Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Provides examples of creating Address objects using different constructor patterns and setters. The no-arg constructor followed by setters is shown, as well as the direct all-args constructor. ```java // No-arg then setters Address addr1 = new Address(); addr1.setStreet("Darwin Rd"); addr1.setDoor("88"); // All-args direct Address addr2 = new Address("Darwin Rd", "88"); // Builder-style (with setters) Address addr3 = new Address(); addr3.setStreet("Main St"); addr3.setDoor("42"); ``` -------------------------------- ### Extended Project Configuration (Stream Module) Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Shows an example configuration for the extended Project class, including the 'forks' parameter. Calling build() finalizes the configuration. ```java Project extended = Project.builder() .name("Vue.js") .language("js") .author("yyx990803") .stars(83000) .forks(10322) .description("A progressive, incrementally-adoptable JavaScript framework") .build(); ``` -------------------------------- ### Create and Name a Thread Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/concurrent-module.md Shows how to create a thread with a specific name using a lambda expression. The thread prints its assigned name to the console upon starting. ```java Thread thread = new Thread(() -> { String name = Thread.currentThread().getName(); System.out.println(name); }, "worker-thread"); thread.start(); ``` -------------------------------- ### Project Model (Lambda Module) Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/types.md Represents a software project with basic metrics. Used in lambda and method reference examples. ```java import lombok.Builder; import lombok.Data; @Data @Builder public class Project { private String name; private String language; private Integer stars; private String description; private String author; } ``` ```java Project project = Project.builder() .name("Blade") .language("java") .stars(3500) .description("Lightning fast framework") .author("biezhi") .build(); ``` -------------------------------- ### Generic Class Usage Examples Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/types.md Demonstrates how to instantiate and use a generic class with different types such as String, Long, and List. This highlights type safety and flexibility. ```java Generic stringGetter = new Generic<>(); String value = stringGetter.getById(1); Generic longGetter = new Generic<>(); Long id = longGetter.getById(100); Generic> listGetter = new Generic<>(); List items = listGetter.getById(1); ``` -------------------------------- ### Handling TimeoutException with CompletableFuture.get() Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md This example demonstrates using get(timeout, unit) to retrieve a CompletableFuture's result with a specified timeout. It includes catching TimeoutException and cancelling the future if the timeout is reached. ```java try { Integer result = future.get(5, TimeUnit.SECONDS); } catch (TimeoutException e) { System.err.println("Task timed out"); future.cancel(true); } catch (ExecutionException e) { System.err.println("Task failed: " + e.getCause()); } ``` -------------------------------- ### Address Model Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/types.md A simple model for physical addresses, used in conjunction with the User model and Optional examples. ```java import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Address { private String street; private String door; } ``` ```java Address addr = new Address("Darwin Rd", "88"); Optional
optional = Optional.of(addr); String street = optional.map(Address::getStreet).orElse("Unknown"); ``` -------------------------------- ### ConcurrentHashMap Usage Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/concurrent-module.md Demonstrates basic put and get operations, including putIfAbsent for conditional insertion in a thread-safe map. ```java ConcurrentHashMap map = new ConcurrentHashMap<>(); map.put("key1", 100); map.putIfAbsent("key1", 200); // Only put if absent Integer value = map.get("key1"); ``` -------------------------------- ### Execute Supplier Asynchronously with supplyAsync Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/completablefuture-module.md Use supplyAsync to execute a Supplier asynchronously and return a result. It runs on the default ForkJoinPool and returns CompletableFuture. Use join() or get() to retrieve the computed value. ```java CompletableFuture integerFuture = CompletableFuture.supplyAsync( () -> 2333 ); ``` ```java // Simple value computation CompletableFuture future = CompletableFuture.supplyAsync(() -> { return "Hello from async task"; }); // Get result String result = future.join(); System.out.println(result); ``` ```java // Compute value with delay CompletableFuture delayedFuture = CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(1); return 42; } catch (InterruptedException e) { throw new IllegalStateException(e); } }); Integer value = delayedFuture.join(); // Waits 1 second ``` -------------------------------- ### Iterate and Print Names Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Applies an action to each element in a stream, commonly used for printing or performing side effects. This example iterates through a list of names and prints each one. ```java names.stream().forEach(name -> System.out.println(name)); ``` -------------------------------- ### Project Data Model Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md A data model representing a software project with repository metrics. Used for stream processing examples. ```java import lombok.Builder; import lombok.Data; @Data @Builder public class Project { private String name; private String language; private Integer stars; private String description; private String author; private Integer forks; } ``` -------------------------------- ### Process Project Stream to Get Names Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/README.md Filters projects by language and extracts their names using the Stream API. ```java List names = projects.stream() .filter(p -> "java".equals(p.getLanguage())) .map(Project::getName) .collect(Collectors.toList()); ``` -------------------------------- ### Timeout with get() and Exception Handling Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Use this to retrieve the result of a CompletableFuture with a maximum wait time. It requires explicit handling of the TimeoutException if the future does not complete in time. ```java try { String result = future.get(5, TimeUnit.SECONDS); } catch (TimeoutException e) { // Handle timeout } ``` -------------------------------- ### Implement Timeout Handling Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/completablefuture-module.md Use `get(timeout, unit)` to set a time limit for a CompletableFuture's execution. If the timeout is reached, a `TimeoutException` is thrown, and the operation can be cancelled. ```java CompletableFuture future = CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(5); return 42; } catch (InterruptedException e) { throw new IllegalStateException(e); } }); try { Integer result = future.get(2, TimeUnit.SECONDS); // Timeout after 2s } catch (TimeoutException e) { System.out.println("Operation timed out"); future.cancel(true); // Cancel the operation } ``` -------------------------------- ### Reduce Stream to Sum with Initial Value Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Performs a reduction operation on stream elements to compute a sum, starting with an initial value. This is a generic way to perform custom aggregations. ```java Integer sum = projects.stream() .collect(reducing(0, Project::getStars, (x, y) -> x + y)); // Returns: Total sum of all stars ``` -------------------------------- ### Execute Runnable Asynchronously with runAsync Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/completablefuture-module.md Use runAsync to execute a Runnable asynchronously without returning a value. It runs on the default ForkJoinPool and returns CompletableFuture. Useful for fire-and-forget tasks or when you need to wait for completion using join() or get(). ```java CompletableFuture helloFuture = CompletableFuture.runAsync( () -> System.out.println("hello future") ); ``` ```java // Simple fire-and-forget CompletableFuture.runAsync(() -> { System.out.println("Task running asynchronously"); }); ``` ```java // Wait for completion CompletableFuture future = CompletableFuture.runAsync(() -> { try { TimeUnit.SECONDS.sleep(2); System.out.println("Delayed task completed"); } catch (InterruptedException e) { e.printStackTrace(); } }); future.join(); // Wait for completion ``` -------------------------------- ### Create Project Instance Using Builder Pattern Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/lambda-module.md Demonstrates creating a Project instance using the Lombok Builder pattern. ```java Project blade = Project.builder() .name("Blade") .language("java") .author("biezhi") .stars(3500) .description("Lightning fast and elegant mvc framework for Java8") .build(); ``` -------------------------------- ### Partial Project Configuration (Lambda Module) Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Demonstrates a partial configuration for the Project class, omitting optional fields like author and description. These omitted fields will default to null. ```java // Partial configuration Project partial = Project.builder() .name("Flask") .language("python") .stars(10500) // author, description omitted (null) .build(); ``` -------------------------------- ### Set Timeout for Future Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Attempt to get the result of a CompletableFuture with a specified timeout. Throws `TimeoutException` if the timeout is exceeded. ```java future.get(5, TimeUnit.SECONDS); ``` -------------------------------- ### Create Project with Builder and Additional Fields Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Create a Project object using a builder, including an additional 'forks' field. Also shows how to build predefined data. ```java // Has additional 'forks' field Project p = Project.builder() .name("Vue") .language("js") .forks(10322) .stars(83000) .build(); // Predefined data List projects = Project.buildData(); ``` -------------------------------- ### Create Project with Builder Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Instantiate a Project object using a builder pattern, setting various properties like name, language, author, stars, and description. ```java Project p = Project.builder() .name("Blade") .language("java") .author("biezhi") .stars(3500) .description("Framework") .build(); ``` -------------------------------- ### Minimal Project Configuration (Lambda Module) Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Shows a minimal configuration for the Project class, setting only the required name and language. Other fields will be null. ```java // Minimal configuration Project minimal = Project.builder() .name("MyProject") .language("java") .build(); ``` -------------------------------- ### Complete Project Configuration (Lambda Module) Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Illustrates a complete configuration for the Project class, setting all available parameters. The resulting object is immutable if fields are declared final. ```java // Complete configuration Project complete = Project.builder() .name("Blade") .language("java") .author("biezhi") .stars(3500) .description("Lightning fast and elegant mvc framework for Java8") .build(); ``` -------------------------------- ### Create and Manage ExecutorService in Java Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Shows how to create different types of ExecutorService and submit tasks. ```java // Create executor ExecutorService executor = Executors.newSingleThreadExecutor(); ExecutorService fixed = Executors.newFixedThreadPool(4); ExecutorService cached = Executors.newCachedThreadPool(); // Submit task executor.submit(() -> System.out.println("Task")); // Shutdown executor.shutdown(); executor.awaitTermination(60, TimeUnit.SECONDS); executor.shutdownNow(); ``` -------------------------------- ### Project Builder Method Chain (Lambda Module) Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Demonstrates the fluent configuration chain for the Project class using Lombok's @Builder annotation. All parameters are optional. ```java Project project = Project.builder() .name(String) .language(String) .stars(Integer) .description(String) .author(String) .build(); ``` -------------------------------- ### Working with Optional in Java Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Shows how to create, transform, and safely extract values from Optional instances. Covers mapping, flatMapping, providing defaults, and safe property reading. ```java // Create Optional instances Optional
empty = Optional.empty(); Optional
nonNull = Optional.of(new Address()); Optional
nullable = Optional.ofNullable(maybeNull); // Transform values Optional street = address.map(Address::getStreet); // Chain Optional results Optional chained = userOptional .flatMap(User::getOptAddress) .map(Address::getStreet); // Extract with default String street = address.map(Address::getStreet).orElse("Unknown"); // Parse safely Optional num = OptionalDemo.parseInt("123"); // Optional.of(123) Optional bad = OptionalDemo.parseInt("abc"); // Optional.empty() // Read property safely int score = demo.readPoint(props, "key"); // Returns value or 0 ``` -------------------------------- ### Build Sample Project Data Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Generates a list of sample Project objects for testing stream operations. This method provides predefined data for demonstration purposes. ```java import java.util.List; public static List buildData() { return List.of( Project.builder().name("Blade").language("Java").stars(3500).forks(2000).build(), Project.builder().name("Tale").language("JavaScript").stars(2600).forks(2300).build(), Project.builder().name("Vue.js").language("JavaScript").stars(83000).forks(10322).build(), Project.builder().name("Flask").language("Python").stars(10500).forks(3000).build(), Project.builder().name("Elves").language("Java").stars(200).forks(100).build() ); } ``` ```java List projects = Project.buildData(); // Use for testing stream operations ``` -------------------------------- ### Sequential Execution with thenApply and thenAccept Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/completablefuture-module.md Demonstrates sequential execution where each task depends on the result of the previous one. thenApply is used for transformations, and thenAccept for consuming the final result without returning a new value. ```java CompletableFuture future = CompletableFuture.supplyAsync(() -> { System.out.println("Task 1"); return "result1"; }) .thenApply(result1 -> { System.out.println("Task 2: using " + result1); return "result2"; }) .thenAccept(result2 -> { System.out.println("Task 3: using " + result2); }); future.join(); // Wait for all tasks ``` -------------------------------- ### Usage of Static Factory Method and Interface Methods Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/default-methods-module.md Shows how to obtain a Calculator instance using the static factory method and then call various abstract and default methods. ```java Calculator calc = Calculator.getInstance(); int sum = calc.add(5, 3); // 8 int diff = calc.subtract(5, 3); // 2 int prod = calc.multiply(5, 3); // 15 int quot = calc.divide(15, 3); // 5 int remainder = calc.mod(10, 3); // 1 ``` -------------------------------- ### Create Lambda Expressions for Project Filtering Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/lambda-module.md Shows how to create lambda expressions for filtering Projects based on language and star count. ```java ProjectPredicate javaFilter = p -> "java".equals(p.getLanguage()); ProjectPredicate starFilter = p -> p.getStars() > 1000; ``` -------------------------------- ### Method References in Java Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Illustrates the use of method references for static methods, instance methods on objects, and constructor references. Useful for concise lambda expressions. ```java // Static method reference List multiples = MethodReference.findNumbers(numbers, MethodReference::multipleOf3); // Method reference on objects projects.stream().map(Project::getName); // Constructor reference Function addrFactory = Address::new; ``` -------------------------------- ### Filter Projects with Predicates Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Demonstrates various ways to filter a list of Project objects using different filter methods and lambda expressions. Includes filtering by stars, language, and custom predicates. ```java // Filter with generic Predicate List result = FilterProjects.filter(projects, p -> p.getStars() > 1000); // Filter Java projects List java = FilterProjects.filterJavaProjects(projects); // Filter by language List py = FilterProjects.filterLanguageProjects(projects, "python"); // Filter by language AND stars List hot = FilterProjects.filterLanguageAndStarProjects(projects, "java", 500); // Filter with custom ProjectPredicate List custom = FilterProjects.filterProjects(projects, p -> p.getAuthor().equals("biezhi")); ``` -------------------------------- ### Async Pipeline with CompletableFuture Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Illustrates building an asynchronous pipeline of operations using CompletableFuture in Java 8. ```java CompletableFuture.supplyAsync(this::fetchData) .thenApply(this::parseData) .thenApply(this::validateData) .exceptionally(e -> { logger.error("Failed", e); return DEFAULT; }) .thenAccept(this::process); ``` -------------------------------- ### Batch Processing with Streams Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Illustrates batch processing of a list of projects using Java 8 Streams API for filtering and mapping. ```java projects.stream() .filter(p -> p.getStars() > 1000) .map(Project::getName) .forEach(System.out::println); ``` -------------------------------- ### Building Collections with Streams Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Shows how to collect elements from a stream into a List using Java 8 Streams and Collectors. ```java List names = projects.stream() .map(Project::getName) .collect(Collectors.toList()); ``` -------------------------------- ### Create User Object with Optional Address Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Instantiate a User object and set their username and an optional address using `Optional.of`. ```java Address addr = new Address("Main St", "42"); // or Address addr = new Address(); addr.setStreet("Main St"); addr.setDoor("42"); User user = new User(); user.setUsername("alice"); user.setOptAddress(Optional.of(addr)); ``` -------------------------------- ### Use Default Methods in Java 8 Interfaces Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Demonstrates calling default methods provided by an interface implementation. ```java Calculator calc = Calculator.getInstance(); // Use methods int add = calc.add(5, 3); // 8 int sub = calc.subtract(5, 3); // 2 int mul = calc.multiply(5, 3); // 15 int div = calc.divide(15, 3); // 5 int mod = calc.mod(10, 3); // 1 (default method) ``` -------------------------------- ### Create Java 8 Streams from Collections, Arrays, and Direct Values Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Demonstrates various ways to create a Stream in Java 8. ```java Stream fromList = list.stream(); Stream fromArray = Arrays.stream(array); Stream direct = Stream.of("a", "b", "c"); ``` -------------------------------- ### User Model with Optional Address Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/types.md Demonstrates user data structure including a traditional nullable address and an Optional-wrapped address for safer handling. ```java import java.util.Optional; import lombok.Data; @Data public class User { private String username; private String password; private Integer age; private Address address; private Optional
optAddress; } ``` ```java User user = new User(); user.setUsername("alice"); user.setAge(30); user.setOptAddress(Optional.of(new Address("Main St", "42"))); Optional street = Optional.of(user) .flatMap(User::getOptAddress) .map(Address::getStreet); ``` -------------------------------- ### Create Stream Directly Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Illustrates creating a stream from a fixed set of values using Stream.of(). ```java Stream stream = Stream.of("hello", "world"); ``` -------------------------------- ### Java 8 Import Summary Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md A summary of common Java 8 imports for functional programming, streams, optionals, concurrency, and collections. ```java // Functional import java.util.function.*; // Stream import java.util.stream.*; import static java.util.stream.Collectors.*; // Optional import java.util.Optional; // Concurrent import java.util.concurrent.*; import java.util.concurrent.atomic.*; // Async import java.util.concurrent.CompletableFuture; // Collections import java.util.*; // Project-specific import io.github.biezhi.java8.lambda.lesson1.*; import io.github.biezhi.java8.optional.*; import io.github.biezhi.java8.stream.*; import io.github.biezhi.java8.concurrent.*; import io.github.biezhi.java8.completablefuture.*; import io.github.biezhi.java8.defaultmethods.*; ``` -------------------------------- ### Create Stream from Collection Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Demonstrates creating a stream from a List. This is a common way to process collections. ```java List list = Arrays.asList("hello", "world"); Stream stream = list.stream(); ``` -------------------------------- ### Define Project Data Model Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/lambda-module.md Defines the Project data model with fields for name, language, stars, description, and author. ```java @Data @Builder public class Project { private String name; private String language; private Integer stars; private String description; private String author; } ``` -------------------------------- ### Address All-Arguments Constructor Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Shows the usage of the all-arguments constructor for the Address class, generated by Lombok's @AllArgsConstructor. This allows direct initialization of street and door. ```java Address addr = new Address(String street, String door); ``` -------------------------------- ### Project Builder Method Chain (Stream Module) Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Presents the builder method chain for the extended Project class in the Stream module, including an additional 'forks' field. The order of builder calls is irrelevant. ```java Project project = Project.builder() .name(String) .language(String) .stars(Integer) .description(String) .author(String) .forks(Integer) .build(); ``` -------------------------------- ### Handling Parsing Failures with Optional in Java Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md Demonstrates how Optional can be used to safely handle parsing failures without throwing exceptions. Parsing errors result in an empty Optional, allowing for a safe fallback value. ```java OptionalDemo demo = new OptionalDemo(); // Parse failures return empty, no exception Optional result = OptionalDemo.parseInt("invalid"); int value = result.orElse(0); // Safe fallback // Properties reading safely handles missing/invalid values int score = demo.readPoint(props, "missing"); // Returns 0, never throws ``` -------------------------------- ### Create Stream from Array Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Shows how to create a stream directly from an array of strings. Useful for processing existing array data. ```java Stream stream = Arrays.stream(new String[]{"hello", "world"}); ``` -------------------------------- ### Create Address Object Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Instantiate an Address object using either a constructor with parameters or setters for street and door. ```java Address addr = new Address("Main St", "42"); // or Address addr = new Address(); addr.setStreet("Main St"); addr.setDoor("42"); ``` -------------------------------- ### Semaphore Usage Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/concurrent-module.md Demonstrates how to use a Semaphore to control the number of threads that can concurrently access a resource. ```java Semaphore semaphore = new Semaphore(3); // Allow 3 concurrent accesses semaphore.acquire(); try { // Protected resource } finally { semaphore.release(); } ``` -------------------------------- ### Create an Empty Optional Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Instantiate an empty Optional object. This is useful when a value might be absent and no default is immediately available. ```java Optional
empty = Optional.empty(); ``` -------------------------------- ### Safe Null Handling with Optional Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Demonstrates safe null handling using Java 8's Optional class, chaining operations without explicit null checks. ```java // Instead of: if (user != null && user.getAddress() != null) ... Optional.ofNullable(user) .flatMap(User::getOptAddress) .ifPresent(addr -> ...); ``` -------------------------------- ### Usage of Default Method 'mod' Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/default-methods-module.md Demonstrates how to call the default 'mod' method on a Calculator instance obtained via the static factory method. ```java Calculator calc = Calculator.getInstance(); int result = calc.mod(10, 3); // Returns: 1 ``` -------------------------------- ### Filter Projects by Stars and Language Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Filters projects based on a minimum star count and a specific language, then collects their names into a list. Requires 'projects' collection and appropriate Project class methods. ```java List names = projects.stream() .filter(p -> p.getStars() > 1000) .filter(p -> "java".equals(p.getLanguage())) .map(Project::getName) .collect(Collectors.toList()); ``` -------------------------------- ### Sort Projects by Stars Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Sorts a stream of projects based on their star count in ascending order and prints each project to the console. Requires a 'projects' stream and a Project class with a getStars() method. ```java projects.stream() .sorted(Comparator.comparing(Project::getStars)) .forEach(System.out::println); ``` -------------------------------- ### Count Projects by Language Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Counts the number of projects in a stream that match a specific language. Ensure the 'projects' collection is available. ```java long count = projects.stream() .filter(p -> "java".equals(p.getLanguage())) .count(); ``` -------------------------------- ### Configure Named and Combined Predicates Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Define reusable predicates for filtering projects based on language and popularity. Combine predicates using 'and' for more complex filtering criteria. ```java // Reusable predicate configuration Predicate javaProjects = p -> "java".equals(p.getLanguage()); Predicate popularProjects = p -> p.getStars() > 500; Predicate combinedFilter = javaProjects.and(popularProjects); List results = FilterProjects.filter(projects, combinedFilter); ``` -------------------------------- ### Fork-Join Pattern for Parallel Processing Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/concurrent-module.md Illustrates the use of the ForkJoinPool for divide-and-conquer parallel processing. It invokes a SumTask to compute the sum of elements in a list. ```java ForkJoinPool pool = new ForkJoinPool(); List list = /* ... */; int sum = pool.invoke(new SumTask(list, 0, list.size())); ``` -------------------------------- ### Collect Stream Elements to Various Collections Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Demonstrates collecting stream elements into different collection types like ArrayList, HashSet, or a custom LinkedList. Also shows averaging and string concatenation. ```java projects.stream() .collect(Collectors.toList()); // Collect to ArrayList projects.stream() .collect(Collectors.toSet()); // Collect to HashSet projects.stream() .collect(Collectors.toCollection(LinkedList::new)); // Custom collection projects.stream() .collect(Collectors.averagingInt(Project::getStars)); // Average projects.stream() .collect(Collectors.joining(",")); // String concatenation ``` -------------------------------- ### ExecutorService Lifecycle Management Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/README.md Creates a fixed thread pool executor and demonstrates its graceful shutdown. ```java ExecutorService executor = Executors.newFixedThreadPool(4); // submit tasks... ConcurrentUtils.stop(executor); ``` -------------------------------- ### Exception Propagation and Catching Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/completablefuture-module.md Demonstrates how exceptions thrown in intermediate stages of a CompletableFuture are wrapped in `CompletionException`. Use `getCause()` to access the original exception. ```java CompletableFuture future = CompletableFuture.supplyAsync(() -> 5) .thenApply(x -> { if (x < 0) throw new IllegalArgumentException("Negative number"); return x * 2; }) .thenApply(x -> x + 1); try { Integer result = future.join(); } catch (CompletionException e) { Throwable cause = e.getCause(); System.out.println("Cause: " + cause.getMessage()); } ``` -------------------------------- ### Address No-Argument Constructor Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Demonstrates the usage of the no-argument constructor for the Address class, generated by Lombok's @NoArgsConstructor. Setters can be used to populate fields. ```java Address addr = new Address(); ``` -------------------------------- ### Java Async Operation Exception Handling Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md Shows how to handle exceptions in asynchronous operations using CompletableFuture. Includes basic exception handling and strategies for timeouts with fallbacks. ```java // BAD - Ignores exceptions CompletableFuture.supplyAsync(this::fetchData) .thenApply(this::processData) .join(); ``` ```java // GOOD - Handles exceptions CompletableFuture.supplyAsync(this::fetchData) .thenApply(this::processData) .exceptionally(ex -> { System.err.println("Error: " + ex.getMessage()); return null; }) .join(); ``` ```java // BETTER - Timeout and fallback CompletableFuture result = CompletableFuture.supplyAsync(this::fetchData) .completeOnTimeout(DEFAULT_DATA, 5, TimeUnit.SECONDS) .exceptionally(ex -> { logger.error("Fetch failed", ex); return FALLBACK_DATA; }); ``` -------------------------------- ### Project Model (Stream Module) Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/types.md An extended project model including fork count, used for stream operations and collectors. ```java import lombok.Builder; import lombok.Data; @Data @Builder public class Project { private String name; private String language; private Integer stars; private String description; private String author; private Integer forks; } ``` ```java public static List buildData() ``` -------------------------------- ### Chaining Transformations with thenApply Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/completablefuture-module.md Use thenApply for map-like operations where each step returns a plain value. The subsequent step receives this value. ```java CompletableFuture future = CompletableFuture.supplyAsync(() -> 5) .thenApply(x -> x * 2) // 5 * 2 = 10 .thenApply(x -> x + 3); // 10 + 3 = 13 Integer result = future.join(); // 13 ``` -------------------------------- ### Safe Stream Usage in Java Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md Illustrates a safe way to use Java Streams by checking for null or empty lists and filtering out null elements within the stream pipeline. This prevents NullPointerExceptions. ```java List projects = Project.buildData(); if (projects != null && !projects.isEmpty()) { Long count = projects.stream() .filter(p -> p != null && p.getStars() != null) .count(); } ``` -------------------------------- ### Grouping Elements with Streams Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Demonstrates grouping elements from a stream into a Map based on a classifier function using Java 8 Streams and Collectors. ```java Map> byLanguage = projects.stream() .collect(Collectors.groupingBy(Project::getLanguage)); ``` -------------------------------- ### Async Execution with Default ForkJoinPool Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Use this when you need simple asynchronous execution without custom thread pool management. It leverages the common ForkJoinPool. ```java CompletableFuture future = CompletableFuture.supplyAsync(() -> 42); ``` -------------------------------- ### Supply Async Computation Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Perform an asynchronous computation that returns a result. Use `join()` to block and retrieve the result. ```java CompletableFuture future = CompletableFuture.supplyAsync(() -> 42); Integer result = future.join(); ``` -------------------------------- ### Common Java Concurrency Imports Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/concurrent-module.md Lists essential import statements for using various concurrency utilities in Java, including ExecutorService, Locks, Semaphores, and atomic variables. ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.ConcurrentHashMap; ``` -------------------------------- ### Java Exception Hierarchy Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md Illustrates the standard Java exception hierarchy, showing the relationship between Throwable, Error, Exception, CheckedException, and RuntimeException. ```text Throwable ├── Error └── Exception ├── CheckedException (extends Exception) └── RuntimeException ├── ArithmeticException ├── IllegalArgumentException ├── NullPointerException ├── IndexOutOfBoundsException └── [others] ``` -------------------------------- ### Java 8 Optional Import Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/README.md Import for the Optional class, used for handling null values gracefully. ```java import java.util.Optional; ``` -------------------------------- ### Static Factory Method: getInstance Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/default-methods-module.md Provides a factory method to obtain a concrete Calculator instance. Static methods in interfaces are a Java 8 feature. ```java static Calculator getInstance() { return new BasicCalculator(); } ``` -------------------------------- ### Producer-Consumer with ExecutorService Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/concurrent-module.md Implements the Producer-Consumer pattern using an ExecutorService with a fixed thread pool. The producer adds items to a queue, and the consumer removes and processes them. ```java ExecutorService executor = Executors.newFixedThreadPool(2); // Producer executor.submit(() -> { for (int i = 0; i < 10; i++) { queue.put(i); } }); // Consumer executor.submit(() -> { while (true) { Integer item = queue.take(); System.out.println("Consumed: " + item); } }); ConcurrentUtils.stop(executor); ``` -------------------------------- ### Java 8 Async CompletableFuture Import Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/README.md Import for CompletableFuture, used for asynchronous programming. ```java import java.util.concurrent.CompletableFuture; ``` -------------------------------- ### Custom Implementation of Calculator Interface Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/types.md Provides a concrete implementation for the abstract methods defined in the Calculator interface. The default 'mod' method is inherited. ```java public class MyCalculator implements Calculator { @Override public int add(int a, int b) { return a + b; } @Override public int subtract(int a, int b) { return a - b; } @Override public int multiply(int a, int b) { return a * b; } @Override public int divide(int a, int b) { if (b == 0) throw new IllegalArgumentException("Division by zero"); return a / b; } // mod() inherited from default method } ``` -------------------------------- ### Execute Tasks with a Custom Executor Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/completablefuture-module.md Provide a custom `ExecutorService` to `supplyAsync` or `runAsync` to control the thread pool used for executing asynchronous tasks. This is crucial for managing resources and performance. ```java ExecutorService executor = Executors.newFixedThreadPool(4); CompletableFuture future = CompletableFuture.supplyAsync( () -> { System.out.println("Running on: " + Thread.currentThread().getName()); return 42; }, executor ); Integer result = future.join(); executor.shutdown(); ``` -------------------------------- ### Calculator Interface Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/types.md An interface demonstrating default and static methods in Java 8. It includes abstract methods for basic arithmetic operations and default/static methods for additional functionality. ```APIDOC ## Calculator Interface ### Description An interface that defines abstract methods for basic arithmetic operations (add, subtract, multiply, divide) and includes a default method for the modulo operation (`mod`) and a static factory method (`getInstance`) to obtain an instance of a concrete implementation. ### Abstract Methods #### add - **Parameters**: `int first`, `int second` - **Returns**: `int` - **Description**: Performs addition of two integers. #### subtract - **Parameters**: `int first`, `int second` - **Returns**: `int` - **Description**: Performs subtraction of two integers. #### multiply - **Parameters**: `int first`, `int second` - **Returns**: `int` - **Description**: Performs multiplication of two integers. #### divide - **Parameters**: `int number`, `int divisor` - **Returns**: `int` - **Description**: Performs division of two integers. ### Default Methods #### mod - **Parameters**: `int first`, `int second` - **Returns**: `int` - **Description**: Calculates the remainder of the division of `first` by `second`. ### Static Methods #### getInstance - **Returns**: `Calculator` - **Description**: A factory method that returns an instance of `BasicCalculator`. ### Implementation Example ```java public class MyCalculator implements Calculator { @Override public int add(int a, int b) { return a + b; } @Override public int subtract(int a, int b) { return a - b; } @Override public int multiply(int a, int b) { return a * b; } @Override public int divide(int a, int b) { if (b == 0) throw new IllegalArgumentException("Division by zero"); return a / b; } // The 'mod' method is inherited from the default method in the Calculator interface. } ``` ``` -------------------------------- ### Provide Default Values for Optional Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Handle cases where an Optional is empty by providing a static default value, a lazily computed default value, or by throwing an exception. ```java String street = address .map(Address::getStreet) .orElse("Unknown"); // Static default String street = address .map(Address::getStreet) .orElseGet(() -> computeDefault()); // Lazy computation String street = address .map(Address::getStreet) .orElseThrow(IllegalArgumentException::new); // Exception on empty ``` -------------------------------- ### Catching IllegalArgumentException in Java Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md Demonstrates how to catch an IllegalArgumentException when performing division by zero. This pattern is useful for handling predictable arithmetic errors. ```java Calculator calc = new BasicCalculator(); try { int result = calc.divide(10, 0); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); // Handle division by zero } ``` -------------------------------- ### Handling Results and Exceptions with CompletableFuture.handle() Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md The handle() method allows processing both the successful result and any exception that occurred within a CompletableFuture. It's versatile for conditional logic based on completion status. ```java CompletableFuture future = CompletableFuture.supplyAsync(() -> { throw new RuntimeException("Error"); }) .handle((result, exception) -> { if (exception != null) { return "Error: " + exception.getMessage(); } return "Success: " + result; }); ``` -------------------------------- ### Basic ExecutorService Task Submission Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/concurrent-module.md Creates a single-threaded executor and submits a task that sleeps for 3 seconds. The task runs asynchronously in a background thread. ```java ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { try { TimeUnit.SECONDS.sleep(3); String name = Thread.currentThread().getName(); System.out.println("task finished: " + name); } catch (InterruptedException e) { System.err.println("task interrupted"); } }); ``` -------------------------------- ### Safe Handling of Null or Empty Lists in Java Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md Provides a best practice for handling potentially null or empty lists before performing operations like filtering. This prevents NullPointerExceptions. ```java List projects = getProjects(); // May be null if (projects != null && !projects.isEmpty()) { List filtered = FilterProjects.filter(projects, p -> p.getStars() > 1000); } ``` -------------------------------- ### Java Null Safety with Lists Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md Demonstrates safe handling of potentially null lists to avoid NullPointerExceptions. Uses ternary operator and Optional for better null management. ```java // BAD List projects = filterProjects.filter(list, p -> p.getStars() > 100); int count = projects.size(); // NPE if list was null ``` ```java // GOOD List projects = filterProjects.filter(list, p -> p.getStars() > 100); int count = projects != null ? projects.size() : 0; ``` ```java // BETTER - Use Optional Optional.ofNullable(projects) .ifPresent(p -> System.out.println(p.size())); ``` -------------------------------- ### Filter Projects by Stars using Lambda Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/README.md Filters a list of projects based on a minimum star count using a lambda expression. ```java List filtered = FilterProjects.filter( projects, p -> p.getStars() > 1000 ); ``` -------------------------------- ### Filter Projects with Generic Predicate Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Use a generic predicate to define filtering logic for a list of projects. Any lambda returning a boolean is acceptable, and predicate composition is possible. ```java List filtered = FilterProjects.filter( projects, project -> project.getStars() > 1000 ); ``` -------------------------------- ### Catching CompletionException with CompletableFuture.join() Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md When using join() on a CompletableFuture, exceptions from the async task are wrapped in a CompletionException. This snippet shows how to catch it and access the original cause. ```java try { Integer result = future.join(); } catch (CompletionException e) { Throwable cause = e.getCause(); System.err.println("Task failed: " + cause.getMessage()); } ``` -------------------------------- ### Chain Operations with thenApply Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Transform the result of a CompletableFuture using `thenApply`. This is equivalent to a map operation. ```java CompletableFuture result = CompletableFuture.supplyAsync(() -> 5) .thenApply(x -> x * 2) .thenApply(x -> x + 3); ``` -------------------------------- ### Address Domain Object Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/optional-module.md Represents a physical address with street and door number, providing no-arg and all-args constructors. ```java import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Data; @Data @NoArgsConstructor @AllArgsConstructor public class Address { private String street; private String door; } ``` -------------------------------- ### Pipeline of Transformations Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/completablefuture-module.md Create a sequence of asynchronous operations where the result of one operation is passed to the next. This is ideal for building complex data processing workflows. ```java CompletableFuture.supplyAsync(this::fetchData) .thenApply(this::parseData) .thenApply(this::validateData) .thenApply(this::storeData) .thenAccept(result -> System.out.println("Stored: " + result)) .exceptionally(ex -> { System.err.println("Pipeline failed: " + ex.getMessage()); return null; }) .join(); ``` -------------------------------- ### API Call with Timeout and Fallback Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/completablefuture-module.md Execute an asynchronous API call and provide a default value if it times out or an alternative value if it fails. This is useful for ensuring a response even when external services are slow or unavailable. ```java private CompletableFuture fetchData(String id) { return CompletableFuture.supplyAsync(() -> callRemoteAPI(id)) .completeOnTimeout("default-value", 5, TimeUnit.SECONDS) .exceptionally(ex -> { System.err.println("API call failed: " + ex.getMessage()); return "fallback-value"; }); } ``` -------------------------------- ### Filter, Map, and Limit Stream Elements Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/stream-module.md Demonstrates lazy evaluation with filter and map operations, followed by limiting the results and collecting them into a list. Use this to process and transform collections based on conditions. ```java public static void main(String[] args) { List projects = Project.buildData(); List names = projects.stream() .filter(p -> { System.out.println(p.getName()); return p.getStars() > 1000; }) .map(p -> { System.out.println(p.getName()); return p.getName(); }) .limit(3) .collect(Collectors.toList()); System.out.println(names); } ``` -------------------------------- ### Run Async Task Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Execute a task asynchronously without returning a result. Useful for fire-and-forget operations. ```java CompletableFuture.runAsync(() -> System.out.println("Task")); ``` -------------------------------- ### Handling IllegalArgumentException for Division in Java Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/errors.md Presents multiple strategies for handling potential IllegalArgumentExceptions during division, including pre-call validation, try-catch blocks, and using a dedicated validation method. ```java Calculator calc = Calculator.getInstance(); // Option 1: Check before calling if (divisor != 0) { result = calc.divide(number, divisor); } else { result = 0; // or handle error } // Option 2: Use try-catch try { result = calc.divide(number, divisor); } catch (IllegalArgumentException e) { System.err.println("Invalid operation: " + e.getMessage()); result = 0; } // Option 3: Validation method private boolean isValidDivisor(int divisor) { return divisor != 0; } if (isValidDivisor(divisor)) { result = calc.divide(number, divisor); } ``` -------------------------------- ### Project Builder Pattern Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/types.md Use the @Builder annotation to construct Project objects using the builder pattern. This is useful for creating complex objects with multiple optional parameters. ```java Project p = Project.builder() .name("Example") .language("java") .stars(100) .build(); ``` -------------------------------- ### Asynchronous Computation with CompletableFuture Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/README.md Performs an asynchronous computation, applies a transformation, and handles potential exceptions. ```java CompletableFuture result = CompletableFuture.supplyAsync(() -> 42) .thenApply(x -> x * 2) .exceptionally(e -> -1); ``` -------------------------------- ### User Domain Object Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/optional-module.md Defines the User domain object with fields for username, password, age, and address (both nullable and Optional wrapped). ```java import java.util.Optional; import lombok.Data; @Data public class User { private String username; private String password; private Integer age; private Address address; private Optional
optAddress; } ``` -------------------------------- ### Create Scheduled Thread Pool Executor Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/configuration.md Use this for tasks that need to be executed after a delay or periodically. ```java ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); ``` -------------------------------- ### Generic Class Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/types.md Demonstrates a generic class `Generic` which allows for type parametrization. It includes a method `getById` that operates on a generic type. ```APIDOC ## Generic ### Description A generic class that allows for type parametrization. It provides a method to retrieve an object of a specific type based on an ID. ### Type Parameters - **T** - None - Represents any type. ### Methods #### getById - **Signature**: `public T getById(Integer id)` - **Description**: Gets an object of type T by its ID. ### Usage Example ```java // Example for Generic Generic stringGetter = new Generic<>(); String value = stringGetter.getById(1); // Example for Generic Generic longGetter = new Generic<>(); Long id = longGetter.getById(100); // Example for Generic> Generic> listGetter = new Generic<>(); List items = listGetter.getById(1); ``` ### Notes - **Type Erasure**: Generic information is not available at runtime. - **Casting Prevention**: Direct casting like `Generic s = (Generic) obj` results in an unchecked cast warning. - **Wildcard Usage**: Supports wildcards such as `Generic`, `Generic`, and `Generic`. ``` -------------------------------- ### Filter Numbers Using Method Reference Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/api-reference/lambda-module.md Filters a list of integers based on a provided predicate. Use this when you need to apply a specific filtering logic to a list, and that logic can be represented by a method reference. ```java List numbers = Arrays.asList(1, 3, 6, 8, 9, 12, 14, 15); List multiplesOf3 = MethodReference.findNumbers(numbers, MethodReference::multipleOf3); // Returns [3, 6, 9, 12, 15] ``` -------------------------------- ### Java 8 Functional Interface Type Signatures Source: https://github.com/hellokaton/learn-java8/blob/master/_autodocs/QUICK-REFERENCE.md Common functional interfaces in Java 8 and their type signatures. ```java Predicate // T -> boolean Function // T -> R Consumer // T -> void Supplier // () -> T Runnable // () -> void Comparator // (T,T) -> int ProjectPredicate // Project -> boolean ```