您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
Java Method Reference 的语法结构如下:
ClassName::methodName
或 InterfaceName::methodName
。::
分隔类名(或接口名)和方法名。以下是几种常见的方法引用示例:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.sort(String::compareToIgnoreCase);
这里,我们使用了 String::compareToIgnoreCase
方法引用来对字符串列表进行排序。
String name = "Alice";
boolean allMatch = names.stream()
.allMatch(name::startsWith);
在这个例子中,我们使用了 name::startsWith
方法引用来检查列表中的所有字符串是否都以给定的名称开头。
Function
接口):List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
.map(Object::toString)
.forEach(System.out::println);
这里,我们使用了 Object::toString
方法引用来将整数列表转换为字符串列表,并使用 System.out::println
方法引用来打印每个字符串。
Supplier
接口):List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
在这个例子中,我们使用了 Integer::intValue
方法引用来将整数列表中的每个元素转换为 int
类型,并使用 sum()
静态方法来计算它们的和。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。