Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...