J
J
Jake Taylor2021-05-02 16:30:55
Java
Jake Taylor, 2021-05-02 16:30:55

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


Here is another way, but you need to somehow cast the values ​​to the int type:
int[] numbers = pattern.splitAsStream(source).toArray(s -> Integer.parseInt(s));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-05-02
@n199a

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 question

Ask a Question

731 491 924 answers to any question