LearnFrenzy
Sign in Take a free test

Generics · Generics Programs · Question 9

Generic validation rules that collect errors in Java Solution, output & explanation

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

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) be reused for Strings and Integers alike.

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