You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java BiConsumer将两个字符串转换为大写?

使用Java BiConsumer转换两个字符串为大写的实现方式

BiConsumer接口的核心是接收两个参数并执行消费操作,无返回值,而String是不可变类型,所以我们无法直接修改传入的原字符串,只能生成新的大写字符串并进行消费(比如打印)或存入外部容器。以下是两种常见实现:

1. 直接打印转换后的结果(最常用场景)

这是BiConsumer最典型的用法——直接处理并输出参数:

BiConsumer<String, String> cons = (x, y) -> {
    String upperX = x.toUpperCase();
    String upperY = y.toUpperCase();
    System.out.println("第一个字符串转大写: " + upperX);
    System.out.println("第二个字符串转大写: " + upperY);
};

// 调用示例
cons.accept("hello", "java");

运行后会输出:

第一个字符串转大写: HELLO
第二个字符串转大写: JAVA

2. 将结果存入外部容器(需要保留结果时)

如果需要后续使用转换后的字符串,可以借助数组、AtomicReference等引用类型容器(因为lambda中访问的外部变量需为有效final):

// 用数组存储转换结果
String[] upperResults = new String[2];
BiConsumer<String, String> cons = (x, y) -> {
    upperResults[0] = x.toUpperCase();
    upperResults[1] = y.toUpperCase();
};

cons.accept("test", "demo");
// 后续可以使用upperResults中的值
System.out.println(upperResults[0]); // 输出TEST
System.out.println(upperResults[1]); // 输出DEMO

关键注意点

  • String的toUpperCase()方法不会修改原字符串,而是返回一个新的大写字符串,这是String不可变性决定的。
  • BiConsumer没有返回值,因此必须通过消费操作(如打印)或外部容器来获取转换后的结果,不能直接从lambda中返回值。

内容的提问来源于stack exchange,提问作者javabeginer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:05:31