001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.util;
016    
017    import java.util.Comparator;
018    
019    /**
020     * @author Brian Wing Shun Chan
021     */
022    public class ObjectValuePairComparator<K, V>
023            implements Comparator<ObjectValuePair<K, V>> {
024    
025            public ObjectValuePairComparator() {
026                    this(true);
027            }
028    
029            public ObjectValuePairComparator(boolean ascending) {
030                    this(true, ascending);
031            }
032    
033            public ObjectValuePairComparator(boolean byKey, boolean ascending) {
034                    _byKey = byKey;
035                    _ascending = ascending;
036            }
037    
038            @Override
039            public int compare(ObjectValuePair<K, V> ovp1, ObjectValuePair<K, V> ovp2) {
040                    if (_byKey) {
041                            Comparable<K> key1 = (Comparable<K>)ovp1.getKey();
042                            Comparable<K> key2 = (Comparable<K>)ovp2.getKey();
043    
044                            if (_ascending) {
045                                    return key1.compareTo((K)key2);
046                            }
047                            else {
048                                    return -(key1.compareTo((K)key2));
049                            }
050                    }
051                    else {
052                            Comparable<V> value1 = (Comparable<V>)ovp1.getValue();
053                            Comparable<V> value2 = (Comparable<V>)ovp2.getValue();
054    
055                            if (_ascending) {
056                                    return value1.compareTo((V)value2);
057                            }
058                            else {
059                                    return -(value1.compareTo((V)value2));
060                            }
061                    }
062            }
063    
064            private boolean _ascending;
065            private boolean _byKey;
066    
067    }