java - 在 Java 中运行 Stream.map() 内部的函数?
问题描述
我想映射一个字符串数组,如果其中一个包含 x 例如,做一些事情,但是,我不知道怎么做。如果有人可以帮助我,那将不胜感激。顺便说一句,这是一个示例代码:
public static void test(String s) {
if (s.contains("h")) {
System.out.println("Yes");
} else {
System.out.println("No");
}
String example = Arrays.stream(example)
.map(s -> {
test(s);
})
.collect(Collectors.toList())
.toString();
}
解决方案
- 您不能对输出
String
和从中创建流的数组使用相同的名称 (example
)。使用String[] input = {"hello", "world"};
然后流式传输String example = Arrays.stream(input)...
- 该
map
方法需要一个Function<T,R>
. 该方法void test(String s)
与它不兼容,因为它的返回类型。它应该返回String
或根本不使用map
。 - 您一次想要很多东西并将它们混合在一起。你想得到结果然后打印出来吗?或者你想单独打印出每个结果而不收集任何东西?或者两者兼而有之 - 立即打印并收集它们?
以下代码段包含您可能需要的所有案例:
public static String test(String s) {
return s.contains("h") ? "Yes" : "No";
}
String[] input = {"hello", "world"};
String example = Arrays.stream(input) // Streaming "hello" and "world"
.map(s -> test(s)) // Converting each word to a result ("Yes" or "No")
.peek(s -> System.out.println(s)) // Printing the result out immediatelly
.collect(Collectors.toList()) // Collecting to List<String>
.toString();
System.out.println(example); // Prints [Yes, No]
几点注意事项:
map(s -> test(s))
应使用方法引用重写:map(YourClass::test)
peek(s -> System.out.println(s))
也应重写:(peek(System.out::println)
收集到 a 的更好方法
String
是collect(Collectors.joining(", "))
:Yes, No
推荐阅读
- python - 使用 pandas 过滤列以仅显示某些字符串位置
- javascript - 如何在数组内打印带有一组对的JavaScript数组
- amazon-ec2 - 在 aws Code Deploy 更新运行实例中的应用程序之后,使用 RunInstances 启动的新 EC2 实例使用 Launch Template 中的陈旧 AMI
- c - 为什么它只在最后一个循环点输出学生的信息?即第19个学生
- xamarin - Xamarin Grid UWP 和 iOS 显示问题
- sql - 更新 SQL 子查询
- android - android bottomSheet 无法以编程方式更新子大小
- android - 如何从 Android 中的备份文件领域数据库中恢复
- python - 如何在 PyQt5 Python 中的 QDial 上显示标记
- firebase - 此项目错误的 Firebase 云存储配额已超出