LearnFrenzy
Sign in Take a free test

Lambda Expressions · Lambda Expressions Programs · Question 5

Password validation with a list of named predicates in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Build password rules as a Map of message → Predicate<String>, check several passwords and print which rules each fails; combine all rules into one predicate with reduce-style and().

Solution
Main.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Map<String, Predicate<String>> rules = new LinkedHashMap<>();
        rules.put("8+ chars", p -> p.length() >= 8);
        rules.put("a digit", p -> p.chars().anyMatch(Character::isDigit));
        rules.put("an uppercase letter", p -> p.chars().anyMatch(Character::isUpperCase));
        rules.put("no spaces", p -> !p.contains(" "));

        Predicate<String> all = p -> true;
        for (Predicate<String> r : rules.values()) all = all.and(r);

        for (String pw : new String[]{"java", "Java 2026", "Lambda2026"}) {
            List<String> failed = new ArrayList<>();
            rules.forEach((msg, rule) -> { if (!rule.test(pw)) failed.add(msg); });
            System.out.println(pw + " -> " + (all.test(pw) ? "valid" : "missing " + failed));
        }
    }
}

Output Verified by compiling and running

java -> missing [8+ chars, a digit, an uppercase letter]
Java 2026 -> missing [no spaces]
Lambda2026 -> valid

Predicates are combined with and(); a starting predicate of p -> true makes the loop simple.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links