如何使用Stream?
找到此行中所有整数的总和String line = "Test 15 lqlq 35 bad 99999 guess 34";
List<String> lineSplitted = Arrays.stream(line.split(" ")).collect(Collectors.toList());
int result = 0;
try {
result = lineSplitted.stream().filter(s -> Integer.parseInt(s)).sum();
}
catch (Exception e) {
}
System.out.println(result);
答案 0 :(得分:6)
你基本上需要:
工作示例:
import java.util.*;
import java.util.stream.*;
public class HelloWorld {
public static void main(String[] args){
String line = "Test 15 lqlq 35 bad 99999 guess 34";
int sum = Arrays
.stream(line.split(" ")) // Convert to an array
.filter((s) -> s.matches("\\d+")) // Only select the numbers
.mapToInt(Integer::parseInt) // Convert to Integers
.sum(); // Sum
System.out.println(sum);
}
}
答案 1 :(得分:5)
如何按每个非数字分割结果:
long sum = Pattern.compile("\\D+").splitAsStream(line)
.filter(s -> !s.isEmpty())
.mapToLong(Long::parseLong).sum()
答案 2 :(得分:3)
还有一种方法,但需要jdk-9:使用Scanner.findAll()
String line = "Test 15 lqlq 35 bad 99999 guess 34";
Scanner scanner = new Scanner(line);
long result = scanner.findAll(Pattern.compile("\\d+"))
.map(MatchResult::group)).mapToLong(Long::parseLong).sum();
System.out.println(result);