001/*-------------------------------------------------------------------------+ 002| | 003| Copyright 2005-2011 the ConQAT Project | 004| | 005| Licensed under the Apache License, Version 2.0 (the "License"); | 006| you may not use this file except in compliance with the License. | 007| You may obtain a copy of the License at | 008| | 009| http://www.apache.org/licenses/LICENSE-2.0 | 010| | 011| Unless required by applicable law or agreed to in writing, software | 012| distributed under the License is distributed on an "AS IS" BASIS, | 013| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 014| See the License for the specific language governing permissions and | 015| limitations under the License. | 016+-------------------------------------------------------------------------*/ 017package org.conqat.lib.commons.lang; 018 019import java.util.Comparator; 020import java.util.function.IntSupplier; 021 022/** 023 * Utility methods that help working with Java objects. 024 */ 025public class ObjectUtils { 026 027 /** 028 * Compares the two given objects. First checks if they are reference-equal. 029 * If not, checks each for <code>null</code>. If both are non-null, calls 030 * <code>object1.compareTo(object2)</code>. 031 * 032 * <code>null</code> values will be ordered before non-null values. 033 */ 034 public static <T extends Comparable<T>> int compareNullSafe(T object1, T object2) { 035 return compareNullSafe(object1, object2, T::compareTo); 036 } 037 038 /** 039 * Compares the two given objects. First checks if they are reference-equal. 040 * If not, checks each for <code>null</code>. If both are non-null, passes 041 * them to the given comparator. 042 * 043 * <code>null</code> values will be ordered before non-null values. 044 */ 045 public static <T> int compareNullSafe(T object1, T object2, Comparator<T> comparator) { 046 if (object1 == object2) { 047 return 0; 048 } 049 if (object1 == null) { 050 return -1; 051 } 052 if (object2 == null) { 053 return 1; 054 } 055 return comparator.compare(object1, object2); 056 } 057 058 /** 059 * Evaluates the given comparisons in order. If all of them evaluate to 0, 060 * returns 0, otherwise returns the first non-zero result. 061 */ 062 public static int compareInOrder(IntSupplier... comparisonSuppliers) { 063 for (IntSupplier comparisonSupplier : comparisonSuppliers) { 064 int comparisonResult = comparisonSupplier.getAsInt(); 065 if (comparisonResult != 0) { 066 return comparisonResult; 067 } 068 } 069 return 0; 070 } 071 072}