Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to get min and max value from a list of Comparables that main contain null values?

I am thinking about something like this:

public static <T extends Comparable<T>> T minOf(T...ts){        
    SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
    return set.first();
}

public static <T extends Comparable<T>> T maxOf(T...ts){
    SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
    return set.last();
}

But is not null safe, which is something I want too.

Do you know a better way to solve this problem?

EDIT:

After the comments I have also tried min():

public static <T extends Comparable<T>> T minOf(T...ts){        
    return Collections.min(Arrays.asList(ts), new Comparator<T>(){

        public int compare(T o1, T o2) {
            if(o1!=null && o2!=null){
                return o1.compareTo(o2);
            }else if(o1!=null){
                return 1;
            }else{
                return -1;  
            }
        }});
}

What do you think of that?

like image 924
user2427 Avatar asked Dec 15 '08 19:12

user2427


People also ask

Does Max work with NULL values?

MAX ignores any null values. MAX returns NULL when there is no row to select. For character columns, MAX finds the highest value in the collating sequence.

How do you avoid NULL values in Max function?

You can use COALESCE() along with aggregate function MAX() for this.

Does Min ignore NULL values SQL?

MIN ignores any null values. With character data columns, MIN finds the value that is lowest in the sort sequence.


1 Answers

What's wrong with Collections.max?

And why do you care about null safety? Are you sure you want to allow nulls to be in your Collection?

like image 82
Pyrolistical Avatar answered Sep 28 '22 11:09

Pyrolistical