Answer the question
In order to leave comments, you need to log in
How to use Matcher in Stream in Java 8?
There is an object of type String , which contains numbers. How, when getting a stream, to use the results of the Matcher in order to create an array of numbers of the primitive type int[] from a String object using Java 8?
Here's what I sketched.
String source = "-1, 2, 3, -5, 999, 5";
source.codePoints()
.filter(matcher.group())
.map(Integer::parseInt)
.toArray(int[]::new);
int[] numbers = pattern.splitAsStream(source).toArray(s -> Integer.parseInt(s));
Answer the question
In order to leave comments, you need to log in
Matcher can generate stream itself:
// Java9+
var integers = Pattern.compile("-?\\d+").matcher(source)
.results() // Stream<MatchResult>
.map(MatchResult::group) // Stream<String>
.map(Integer::valueOf)
.toArray(Integer[]::new);
// Java8
Integer[] integersJ8 = Pattern.compile(",")
.splitAsStream(source)
.map(String::trim)
.map(Integer::valueOf)
.toArray(Integer[]::new);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question