001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
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 KeyValuePairComparator implements Comparator<KeyValuePair> {
023    
024            public KeyValuePairComparator() {
025                    this(true);
026            }
027    
028            public KeyValuePairComparator(boolean ascending) {
029                    this(true, ascending);
030            }
031    
032            public KeyValuePairComparator(boolean byKey, boolean ascending) {
033                    _byKey = byKey;
034                    _ascending = ascending;
035            }
036    
037            public int compare(KeyValuePair kvp1, KeyValuePair kvp2) {
038                    if (_byKey) {
039                            String key1 = kvp1.getKey();
040                            String key2 = kvp2.getKey();
041    
042                            if (_ascending) {
043                                    return key1.compareTo(key2);
044                            }
045                            else {
046                                    return -(key1.compareTo(key2));
047                            }
048                    }
049                    else {
050                            String value1 = kvp1.getValue();
051                            String value2 = kvp2.getValue();
052    
053                            if (_ascending) {
054                                    return value1.compareTo(value2);
055                            }
056                            else {
057                                    return -(value1.compareTo(value2));
058                            }
059                    }
060            }
061    
062            private boolean _byKey;
063            private boolean _ascending;
064    
065    }