Scanner findAll(Pattern) in Java

findAll(Pattern): This method is available in java.util.Scanner class of Java.

Syntax:

Stream<MatchResult> java.util.Scanner.findAll(Pattern pattern)

This method takes one argument. This method returns a stream of match results from this scanner.

Parameters: One parameter is required for this method.

pattern: the pattern to be matched.

Returns: a sequential stream of match results.

Throws:

1. NullPointerException - if the pattern is null.

2. IllegalStateException - if this scanner is closed.

Approach 1: When no exception

Java

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class ScannerfindAll {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        Pattern pattern = Pattern.compile("[a-z]");

        Stream<MatchResult> stream = scanner.findAll(pattern);
        System.out.println(stream.count());

        scanner.close();
    }
}

Output:

8


Approach 2: NullPointerException

Java

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class ScannerfindAll {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        Pattern pattern = null;

        Stream<MatchResult> stream = scanner.findAll(pattern);
        System.out.println(stream.count());

        scanner.close();
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Scanner.findAll(Scanner.java:2915)


Approach 3: IllegalStateException

Java

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class ScannerfindAll {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        Pattern pattern = Pattern.compile("[a-z]");

        scanner.close();
        Stream<MatchResult> stream = scanner.findAll(pattern);
        System.out.println(stream.count());

    }
}

Output:

Exception in thread "main" java.lang.IllegalStateException: Scanner closed at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150) at java.base/java.util.Scanner.findAll(Scanner.java:2916)


No comments:

Post a Comment