HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Generic predicate in Java 8

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
genericjavapredicate

Problem

Use Case

Creating a generic and reusable predicate with closures that supports Float, Double, Integer, float, double, and integer.

Problem

Extending "Number" doesn't allow for the modulo operator.

Code

Below is the form I'd like the code to be. However, Number doesn't support the modulo function.

public  Predicate isDivisibleBy(T divisor) {
    return (T dividend) -> dividend % divisor == 0;
}


Current Solution

The current solution I have uses method overloading, but just doesn't seem DRY. How can I improve this code?

public Predicate isDivisibleBy(Integer divisor) {
    return dividend -> dividend % divisor == 0;
}

public Predicate isDivisibleBy(Float divisor) {
    return dividend -> dividend % divisor == 0;
}

public Predicate isDivisibleBy(Double divisor) {
    return dividend -> dividend % divisor == 0;
}

Solution

Even though Number doesn't provide any methods to check for divisibility directly, it does provide a method to make the Number into a double, and as we all know, doubles do support the % operator.

Other slight modifications:

  • Your method can be static



  • You don't need to specify the (T dividend) ->, simply using dividend -> is enough.



Final:

public static  Predicate isDivisibleBy(T divisor) {
    return dividend -> dividend.doubleValue() % divisor.doubleValue() == 0;
}


I have tested this code for many cases using a for-loop, and it works mostly fine.

I had one problem with using Long though as the Long value = -195798407404780179L was converted into -1.95798407404780192E17, which loses some accuracy. So it seems like you need a special case for Long:

public static Predicate isDivisibleBy(Long divisor) {
    return dividend -> dividend % divisor == 0;
}


However, be aware that there are some primitive variants available for Predicate:

  • IntPredicate



  • LongPredicate



  • DoublePredicate

Code Snippets

public static <T extends Number> Predicate<T> isDivisibleBy(T divisor) {
    return dividend -> dividend.doubleValue() % divisor.doubleValue() == 0;
}
public static Predicate<Long> isDivisibleBy(Long divisor) {
    return dividend -> dividend % divisor == 0;
}

Context

StackExchange Code Review Q#57200, answer score: 4

Revisions (0)

No revisions yet.