Write a generic Rule<T> record (message + Predicate<? super T>) and a validate(T, List<Rule<T>>) method that returns all failed messages; validate a username String and an age Integer.
Solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
record Rule<T>(String message, Predicate<? super T> test) {
static <T> Rule<T> of(String message, Predicate<? super T> test) { return new Rule<>(message, test); }
}
public class Main {
static <T> List<String> validate(T value, List<Rule<T>> rules) {
List<String> errors = new ArrayList<>();
for (Rule<T> r : rules) if (!r.test().test(value)) errors.add(r.message());
return errors;
}
public static void main(String[] args) {
Predicate<Object> notNull = o -> o != null;
List<Rule<String>> username = List.of(
Rule.of("required", notNull),
Rule.of("3-12 characters", s -> s != null && s.length() >= 3 && s.length() <= 12),
Rule.of("lower case letters/digits only", s -> s != null && s.matches("[a-z0-9]*")));
List<Rule<Integer>> age = List.of(Rule.of("required", notNull), Rule.of("must be 18-60", a -> a != null && a >= 18 && a <= 60));
for (String u : new String[]{"asha21", "Al", null}) System.out.println(u + " -> " + validate(u, username));
System.out.println(validate(17, age) + " " + validate(30, age));
}
}
Output Verified by compiling and running
asha21 -> []
Al -> [3-12 characters, lower case letters/digits only]
null -> [required, 3-12 characters, lower case letters/digits only]
[must be 18-60] []
Predicate super T> lets one general rule (notNull, a Predicate
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!