Min / max function of two Comparables

From java.util.Collections: Collections.max() and Collections.min() Comparable<C> a = …; Comparable<C> b = …; Comparable<C> min = Collections.min(Arrays.asList(a,b)); From org.apache.commons.lang3.ObjectUtils : ObjectUtils.max() and ObjectUtils.min() Comparable<C> a = …; Comparable<C> b = …; Comparable<C> min = ObjectUtils.min(a, b); Apache Commons has less overhead and is able to handle null values, but it is a third party library.

What determines ascending or descending order in Comparator / Comparable collection class?

What is logic behind ordering object elements? how “(this.grade – s.grade)” if positive 1 moves “this.grade” front and puts “s.grade” next in order, why not other way around? Using negative numbers to say “this is less than that”, positive numbers to say “this is more than that” and 0 to say “these 2 things are … Read more

Comparable and Comparator contract with regards to null

Comparable doesn’t allow null simply because: a.compareTo(b) == -b.compareTo(a) for all objects a and b where !a.equals(b). More specifically: a.equals(b) ? b.equals(a) && a.compareTo(b) == 0 && b.compareTo(a) == 0 && a.hashCode() == b.hashCode() : !b.equals(a) && a.compareTo(b) != 0 && a.compareTo(b) == -b.compareTo(a) must evaluate to true to satisfy the relevant contracts. So null … Read more

Why is Stream.sorted not type-safe in Java 8?

Essentially, you’re asking if there’s a way to tell the compiler, “hey, this one method requires the type parameter match more specific bounds than defined at the class level“. This is not possible in Java. Such a feature may be useful but I’d also expect confusing and/or complicated. There’s also no way to make Stream.sorted() … Read more

Comparing the values of two generic Numbers

This should work for all classes that extend Number, and are Comparable to themselves. By adding the & Comparable you allow to remove all the type checks and provides runtime type checks and error throwing for free when compared to Sarmun answer. class NumberComparator<T extends Number & Comparable> implements Comparator<T> { public int compare( T … Read more

What do the return values of Comparable.compareTo mean in Java?

Official Definition From the reference docs of Comparable.compareTo(T): Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)