Java BooleanSupplier 接口
最后修改时间:2025 年 4 月 16 日
java.util.function.BooleanSupplier
接口代表一个返回布尔值的供应商。它是一个函数式接口,具有单个抽象方法 getAsBoolean
。BooleanSupplier 不接受任何参数,但产生一个布尔结果。
BooleanSupplier
是 Java 8 中添加的 Java 函数式编程实用程序的一部分。当您需要惰性评估或生成布尔条件时,它非常有用。该接口经常与 lambda 表达式和方法引用一起使用。
BooleanSupplier 接口概述
BooleanSupplier
接口包含一个抽象方法。与其他函数式接口不同,它不提供默认或静态方法。它的简单性使其易于用于布尔值生成。
@FunctionalInterface public interface BooleanSupplier { boolean getAsBoolean(); }
上面的代码显示了 BooleanSupplier
接口的结构。它使用 @FunctionalInterface 进行注解,以表明其单一抽象方法的性质。该接口不使用泛型,因为它始终返回一个基本布尔值。
BooleanSupplier 的基本用法
使用 BooleanSupplier 的最简单方法是使用 lambda 表达式。我们在 getAsBoolean 方法中定义如何生成布尔值。示例展示了随机布尔值生成。
package com.zetcode; import java.util.function.BooleanSupplier; import java.util.Random; public class Main { public static void main(String[] args) { // Create a random boolean supplier BooleanSupplier randomBoolean = () -> new Random().nextBoolean(); // Get several random values System.out.println("Random boolean 1: " + randomBoolean.getAsBoolean()); System.out.println("Random boolean 2: " + randomBoolean.getAsBoolean()); System.out.println("Random boolean 3: " + randomBoolean.getAsBoolean()); // Simple condition supplier BooleanSupplier isEvening = () -> java.time.LocalTime.now().getHour() > 18; System.out.println("Is evening? " + isEvening.getAsBoolean()); } }
此示例演示了使用 lambda 表达式的基本 BooleanSupplier 用法。randomBoolean 供应商生成随机的真/假值。isEvening 供应商检查当前时间是否在下午 6 点之后。每次调用 getAsBoolean 都会重新评估条件。
带有方法引用的 BooleanSupplier
当现有方法与其签名匹配时,可以使用方法引用来实现 BooleanSupplier。这为不带参数的布尔值返回方法提供了更简洁的语法。
package com.zetcode; import java.util.function.BooleanSupplier; public class Main { private static boolean checkSystemStatus() { // Simulate some system check return Math.random() > 0.5; } private boolean isDatabaseConnected() { // Simulate database connection check return true; } public static void main(String[] args) { // Static method reference BooleanSupplier statusCheck = Main::checkSystemStatus; System.out.println("System status: " + statusCheck.getAsBoolean()); // Instance method reference Main main = new Main(); BooleanSupplier dbCheck = main::isDatabaseConnected; System.out.println("Database connected: " + dbCheck.getAsBoolean()); } }
此示例展示了带有方法引用的 BooleanSupplier。statusCheck 使用静态方法引用,而 dbCheck 使用实例方法引用。当现有方法与函数式接口匹配时,方法引用提供更简洁的语法。
BooleanSupplier 在条件执行中
BooleanSupplier 对于惰性评估条件很有用。仅在需要时才计算布尔值,这可以在某些情况下提高性能。
package com.zetcode; import java.util.function.BooleanSupplier; public class Main { public static void main(String[] args) { // Expensive condition check BooleanSupplier hasEnoughResources = () -> { System.out.println("Checking resources..."); // Simulate expensive computation try { Thread.sleep(1000); } catch (InterruptedException e) {} return Runtime.getRuntime().freeMemory() > 100_000_000; }; // Condition is only evaluated when needed System.out.println("Starting operation..."); if (hasEnoughResources.getAsBoolean()) { System.out.println("Operation completed"); } else { System.out.println("Insufficient resources"); } } }
此示例演示了使用 BooleanSupplier 的惰性评估。仅在调用 getAsBoolean 时才执行昂贵的资源检查。当条件评估成本高昂且可能并非总是需要时,此模式很有用。
BooleanSupplier 在 Optional 中
BooleanSupplier 可以与 Optional 的 filter 方法一起使用以创建条件逻辑。这允许根据动态条件对 Optional 值进行更具表现力的过滤。
package com.zetcode; import java.util.Optional; import java.util.function.BooleanSupplier; public class Main { public static void main(String[] args) { Optionalname = Optional.of("Alice"); // Dynamic condition supplier BooleanSupplier isLongName = () -> name.get().length() > 4; // Use supplier in Optional filter name.filter(n -> isLongName.getAsBoolean()) .ifPresent(n -> System.out.println(n + " has a long name")); // Another example with different condition BooleanSupplier isVowelStart = () -> { String first = name.get().substring(0, 1).toLowerCase(); return "aeiou".contains(first); }; name.filter(n -> isVowelStart.getAsBoolean()) .ifPresent(n -> System.out.println(n + " starts with vowel")); } }
此示例展示了与 Optional 一起使用的 BooleanSupplier。isLongName 供应商动态检查名称长度。isVowelStart 供应商检查第一个字母。两个条件仅在 Optional 处理期间需要时才进行评估。
用于配置检查的 BooleanSupplier
BooleanSupplier 是配置或功能标志检查的理想选择。可以更改实际的检查实现,而无需修改使用该供应商的客户端代码。
package com.zetcode; import java.util.function.BooleanSupplier; public class Main { private static boolean isFeatureEnabledInDB() { // Simulate database check return true; } private static boolean isFeatureEnabledInConfig() { // Simulate config file check return false; } public static void main(String[] args) { // Choose implementation strategy BooleanSupplier featureCheck = args.length > 0 ? Main::isFeatureEnabledInDB : Main::isFeatureEnabledInConfig; if (featureCheck.getAsBoolean()) { System.out.println("Feature is enabled"); // Execute feature code } else { System.out.println("Feature is disabled"); } } }
此示例演示了将 BooleanSupplier 用于功能标志。可以轻松交换实际的检查实现(数据库与配置文件)。客户端代码仅依赖于 BooleanSupplier 接口,而不是实现。
BooleanSupplier 在流操作中
BooleanSupplier 可以与流一起使用以控制操作或过滤。虽然不如其他函数式接口常见,但它对于动态流控制很有用。
package com.zetcode; import java.util.function.BooleanSupplier; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { // Dynamic limit for stream processing BooleanSupplier processMore = () -> Math.random() > 0.3; IntStream.iterate(1, i -> i + 1) .takeWhile(i -> processMore.getAsBoolean()) .limit(10) // safety limit .forEach(System.out::println); // Another example with filtering BooleanSupplier includeNegatives = () -> System.currentTimeMillis() % 2 == 0; IntStream.of(-5, -3, -1, 0, 1, 3, 5) .filter(i -> i >= 0 || includeNegatives.getAsBoolean()) .forEach(System.out::println); } }
此示例展示了流操作中的 BooleanSupplier。processMore 供应商随机停止处理。includeNegatives 供应商根据当前时间切换。两者都演示了基于布尔条件的动态流控制。
BooleanSupplier 用于重试逻辑
BooleanSupplier 非常适合实现重试逻辑模式。它可以封装成功条件检查,同时保持关于实现细节的灵活性。
package com.zetcode; import java.util.function.BooleanSupplier; public class Main { private static int attemptCount = 0; public static void main(String[] args) { // Operation that might need retries BooleanSupplier operationSuccessful = () -> { attemptCount++; System.out.println("Attempt " + attemptCount); // Simulate operation that might fail return Math.random() > 0.7; }; // Retry logic int maxAttempts = 5; while (!operationSuccessful.getAsBoolean() && attemptCount < maxAttempts) { System.out.println("Retrying..."); } if (attemptCount >= maxAttempts) { System.out.println("Operation failed after " + maxAttempts + " attempts"); } else { System.out.println("Operation succeeded on attempt " + attemptCount); } } }
此示例演示了带有 BooleanSupplier 的重试逻辑。operationSuccessful 供应商模拟可能失败的操作。重试循环将持续到成功或达到最大尝试次数。条件检查在供应商中被干净地封装。
来源
在本文中,我们介绍了 Java BooleanSupplier 接口的基本用法模式。理解这些概念有助于在 Java 应用程序中编写更灵活和更具表现力的条件检查代码。
作者
列出所有Java教程。