| 1 | |
package org.webslinger.collections; |
| 2 | |
|
| 3 | |
import java.util.Comparator; |
| 4 | |
import java.util.Map; |
| 5 | |
|
| 6 | 0 | public class KeyedMapEntryComparator implements Comparator<Map> { |
| 7 | |
protected final String key; |
| 8 | |
protected final boolean direction; |
| 9 | |
|
| 10 | 1 | public KeyedMapEntryComparator(String key, boolean direction) { |
| 11 | 1 | this.key = key; |
| 12 | 1 | this.direction = direction; |
| 13 | 1 | } |
| 14 | |
|
| 15 | |
public int compare(Map left, Map right) { |
| 16 | 15 | Comparable v1 = (Comparable) left.get(key); |
| 17 | 15 | Comparable v2 = (Comparable) right.get(key); |
| 18 | |
int r; |
| 19 | 15 | if (v1 == null) { |
| 20 | 0 | r = v2 != null ? -1 : 0; |
| 21 | 15 | } else if (v2 == null) { |
| 22 | 0 | r = 1; |
| 23 | |
} else { |
| 24 | 15 | r = v1.compareTo(v2); |
| 25 | |
} |
| 26 | 15 | if (r != 0) return direction ? -r : r; |
| 27 | 0 | return left.equals(right) ? 0 : direction ? 1 : -1; |
| 28 | |
} |
| 29 | |
|
| 30 | |
public int hashCode() { |
| 31 | 6 | return getClass().hashCode() ^ key.hashCode() ^ (direction ? Boolean.TRUE : Boolean.FALSE).hashCode(); |
| 32 | |
} |
| 33 | |
|
| 34 | |
public boolean equals(Object o) { |
| 35 | 0 | if (!(o instanceof KeyedMapEntryComparator)) return false; |
| 36 | 0 | KeyedMapEntryComparator other = (KeyedMapEntryComparator) o; |
| 37 | 0 | return key.equals(other.key) && direction == other.direction; |
| 38 | |
} |
| 39 | |
} |