1

Find if an input String is valid - the criteria is String length greater than 5 and characters must be a-z, A-Z or 0-9.

Valid strings: aA12Z22, qwerty, ABCDEF0

Not valid: 13A, 12CrW#, @**=_+

I am trying to get it right using Java 8 streams. I have a solution here. The question - is there a better way of doing this (using streams)?

boolean valid = Stream.of(string)
    .flatMapToInt(s -> {
        if (s.length() < 5) return IntStream.of(42); // 42 is a '*' char
        else return s.chars();
        })
    .mapToObj(i -> (char) i)
    .allMatch(c -> Character.isLetterOrDigit(c));
System.out.println(valid);
2
  • 3
    Why not just use regex: string.matches("[A-Za-z0-9]{5,}")? Streams seem unnecessary, hard and inefficient. Commented Sep 8, 2017 at 11:06
  • Can you explain why do you want to do it using stream api? what benefit does it offer compared to regex ? Commented Sep 8, 2017 at 11:18

1 Answer 1

8

Personally, I'd use regex:

boolean valid = string.matches("[A-Za-z0-9]{5,}");

But if you're going to use streams, I'd do it like this:

boolean valid =
    s.length() >= 5 &&
    s.chars().allMatch(Character::isLetterOrDigit);

Noting that Character.isLetterOrDigit may match more characters than you want (e.g. १२३). You could additionally check that c < 128.

Sign up to request clarification or add additional context in comments.

2 Comments

smart solution !
Both the solutions answer my question. The first is precise and compact (and more efficient as you had mentioned) and the second is easily readable and maintainable. Thanks for replying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.