001/*
002 * Copyright 2002-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.util.comparator;
018
019import java.util.Comparator;
020
021import org.springframework.lang.Nullable;
022import org.springframework.util.Assert;
023
024/**
025 * A Comparator that will safely compare nulls to be lower or higher than
026 * other objects. Can decorate a given Comparator or work on Comparables.
027 *
028 * @author Keith Donald
029 * @author Juergen Hoeller
030 * @since 1.2.2
031 * @param <T> the type of objects that may be compared by this comparator
032 * @see Comparable
033 */
034public class NullSafeComparator<T> implements Comparator<T> {
035
036        /**
037         * A shared default instance of this comparator, treating nulls lower
038         * than non-null objects.
039         * @see Comparators#nullsLow()
040         */
041        @SuppressWarnings("rawtypes")
042        public static final NullSafeComparator NULLS_LOW = new NullSafeComparator<>(true);
043
044        /**
045         * A shared default instance of this comparator, treating nulls higher
046         * than non-null objects.
047         * @see Comparators#nullsHigh()
048         */
049        @SuppressWarnings("rawtypes")
050        public static final NullSafeComparator NULLS_HIGH = new NullSafeComparator<>(false);
051
052
053        private final Comparator<T> nonNullComparator;
054
055        private final boolean nullsLow;
056
057
058        /**
059         * Create a NullSafeComparator that sorts {@code null} based on
060         * the provided flag, working on Comparables.
061         * <p>When comparing two non-null objects, their Comparable implementation
062         * will be used: this means that non-null elements (that this Comparator
063         * will be applied to) need to implement Comparable.
064         * <p>As a convenience, you can use the default shared instances:
065         * {@code NullSafeComparator.NULLS_LOW} and
066         * {@code NullSafeComparator.NULLS_HIGH}.
067         * @param nullsLow whether to treat nulls lower or higher than non-null objects
068         * @see Comparable
069         * @see #NULLS_LOW
070         * @see #NULLS_HIGH
071         */
072        @SuppressWarnings("unchecked")
073        private NullSafeComparator(boolean nullsLow) {
074                this.nonNullComparator = ComparableComparator.INSTANCE;
075                this.nullsLow = nullsLow;
076        }
077
078        /**
079         * Create a NullSafeComparator that sorts {@code null} based on the
080         * provided flag, decorating the given Comparator.
081         * <p>When comparing two non-null objects, the specified Comparator will be used.
082         * The given underlying Comparator must be able to handle the elements that this
083         * Comparator will be applied to.
084         * @param comparator the comparator to use when comparing two non-null objects
085         * @param nullsLow whether to treat nulls lower or higher than non-null objects
086         */
087        public NullSafeComparator(Comparator<T> comparator, boolean nullsLow) {
088                Assert.notNull(comparator, "Non-null Comparator is required");
089                this.nonNullComparator = comparator;
090                this.nullsLow = nullsLow;
091        }
092
093
094        @Override
095        public int compare(@Nullable T o1, @Nullable T o2) {
096                if (o1 == o2) {
097                        return 0;
098                }
099                if (o1 == null) {
100                        return (this.nullsLow ? -1 : 1);
101                }
102                if (o2 == null) {
103                        return (this.nullsLow ? 1 : -1);
104                }
105                return this.nonNullComparator.compare(o1, o2);
106        }
107
108
109        @Override
110        @SuppressWarnings("unchecked")
111        public boolean equals(@Nullable Object other) {
112                if (this == other) {
113                        return true;
114                }
115                if (!(other instanceof NullSafeComparator)) {
116                        return false;
117                }
118                NullSafeComparator<T> otherComp = (NullSafeComparator<T>) other;
119                return (this.nonNullComparator.equals(otherComp.nonNullComparator) && this.nullsLow == otherComp.nullsLow);
120        }
121
122        @Override
123        public int hashCode() {
124                return this.nonNullComparator.hashCode() * (this.nullsLow ? -1 : 1);
125        }
126
127        @Override
128        public String toString() {
129                return "NullSafeComparator: non-null comparator [" + this.nonNullComparator + "]; " +
130                                (this.nullsLow ? "nulls low" : "nulls high");
131        }
132
133}