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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!