Reputation: 549
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
Reputation: 13964
You basically need to:
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
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
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