Java 8 Streams取String线的总和

时间:2017-06-23 12:06:00

标签: java lambda java-8 java-stream

如何使用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);

3 个答案:

答案 0 :(得分:6)

你基本上需要:

  1. 将字符串转换为数组
  2. 过滤掉非数字
  3. 将数字字符串转换为数字类型
  4. 总结他们
  5. 工作示例:

    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);