Spongi
Spongi

Reputation: 549

Java 8 Streams taking the sum of String line

How can i find sum of all integers in this line using 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);

Upvotes: 3

Views: 6391

Answers (3)

Jason
Jason

Reputation: 13964

You basically need to:

  1. Convert the string to array
  2. Filter out non-numbers
  3. Convert the number strings to number types
  4. Sum them

Working example:

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

Upvotes: 8

Eugene
Eugene

Reputation: 120848

There's one more way, but requires jdk-9: use 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);

Upvotes: 3

Flown
Flown

Reputation: 11740

How about splitting the result by every non-digit:

long sum = Pattern.compile("\\D+").splitAsStream(line)
                  .filter(s -> !s.isEmpty())
                  .mapToLong(Long::parseLong).sum()

Upvotes: 5

Related Questions