Flatmap example

Paul Sandoz paul.sandoz at oracle.com
Mon Dec 2 04:33:52 PST 2013


Hi,

You are using a raw type for the List of Pattern, which is making it difficult for the compiler to infer types. Try this:

        List<Pattern> patterns = Arrays.asList(Pattern.compile("Current.*?[/|]"),
                                               Pattern.compile("[0-9]+(/,|/|)"));

        patterns.stream()
                .flatMap(new Function<Pattern, Stream<String>>() {
                    @Override
                    public Stream<String> apply(Pattern p) {
                        return source.stream()
                                .map(p::matcher)
                                .filter(Matcher::find)
                                .map(Matcher::group);
                    }
                })
                .forEach(System.out::println);

        patterns.stream()
                .flatMap(p -> source.stream()
                        .map(p::matcher)
                        .filter(Matcher::find)
                        .map(Matcher::group))
                .forEach(System.out::println);

Previously i thought you wanted to do layered matching e.g. match a line with pattern P1, then match the result of that with pattern P2 and so on. 

From your example i see that you wan to apply the pattern N times to the same source of lines to produce N different results (which may be getting into aspects of forked streams previously discussed). So i may have confused you with my suggestion of flatMap. 

A potential problem with your current use of flatMap is that it has munged the results so that the association of the Pattern to matched result is now lost.

Paul.





More information about the lambda-dev mailing list