如果我提供的输入为 pass@123 jes@234 12345 human。 输出应打印为 pass@123 jes@234 单行,中间有空格。 但它打印为 pass@123jes@234 ,没有任何空格。 以下是我的代码。
List<String> splitList = Arrays.asList(ans.split(" "));
splitList.stream().filter(s -> !s.matches("[0-9]+") &&
!s.matches("[a-zA-Z]+") && s.length() > 5)
.collect(Collectors.toList()).forEach(System.out::print);
我尝试提供 System.out.print,但打印的输出之间没有空格。
我建议使用
Collectors.joining
这里有一些有用的文档,还有一些其他有用的收集器。
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
示例代码
import java.util.Arrays;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
String ans = "pass@123 jes@234 12345 human";
final String space = " ";
String line = Arrays.stream(ans.split(space))// you can use Arrays.stream directly, without calling Arrays.asList first
.filter(giveMeSomeMeaningFulName()) //separated into separate method to improve readability
.collect(Collectors.joining(space));//Collectors.joining join the strings with the provided string as separator
System.out.println(line);
}
private static Predicate<? super String> giveMeSomeMeaningFulName() {
return s -> !s.matches("[0-9]+") && !s.matches("[a-zA-Z]+") && s.length() > 5;
}
}
Collectors.joining(CharSequence delimiter)
方法。例如:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class JoiningExample {
public static void main(String[] args) {
String ans = "pass@123 jes@234 12345 human";
List<String> splitList = Arrays.asList(ans.split(" "));
String result = splitList.stream().filter(s -> !s.matches("[0-9]+") &&
!s.matches("[a-zA-Z]+") && s.length() > 5)
.collect(Collectors.joining(" "));
System.out.println(result); // Output: "pass@123 jes@234"
}
}