Check if string contains only digits in Java 8 Lambda

Write a Java 8 program that checks if the given string contains only digits.

Java 8 program to Check if contains only digits

public final class Strings {

    public static boolean containsOnlyDigit(String str) {

        if (str == null || str.isBlank()) {
            // or throw IllegalArgumentException
            return false;
        }

        return !str.chars()
                .anyMatch(n -> !Character.isDigit(n));
    }
}

Test

public class Main {

    private static final String ONLY_DIGITS = "123456789";
    
    private static final String NOT_ONLY_DIGITS = "123456789A";
    
    public static void main(String[] args) {

        System.out.println("Input text with only digits: \n" + ONLY_DIGITS + "\n");
        System.out.println("Input text with other characters: \n" + NOT_ONLY_DIGITS + "\n");
                
        System.out.println("Java 8, functional-style solution:");
        
        boolean onlyDigitsV31 = Strings.containsOnlyDigits(ONLY_DIGITS);
        boolean onlyDigitsV32 = Strings.containsOnlyDigits(NOT_ONLY_DIGITS);
        System.out.println("Contains only digits: " + onlyDigitsV31);
        System.out.println("Contains only digits: " + onlyDigitsV32);        
    }
}

Output:

Input text with only digits: 
123456789

Input text with other characters: 
123456789A

Java 8, functional-style solution:
Contains only digits: true
Contains only digits: false

Comments