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 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            @Override
038            public int compare(KeyValuePair kvp1, KeyValuePair kvp2) {
039                    if (_byKey) {
040                            String key1 = kvp1.getKey();
041                            String key2 = kvp2.getKey();
042    
043                            if (_ascending) {
044                                    return key1.compareTo(key2);
045                            }
046                            else {
047                                    return -(key1.compareTo(key2));
048                            }
049                    }
050                    else {
051                            String value1 = kvp1.getValue();
052                            String value2 = kvp2.getValue();
053    
054                            if (_ascending) {
055                                    return value1.compareTo(value2);
056                            }
057                            else {
058                                    return -(value1.compareTo(value2));
059                            }
060                    }
061            }
062    
063            private boolean _ascending;
064            private boolean _byKey;
065    
066    }