1 24 package org.ofbiz.base.util.collections; 25 26 import java.util.Comparator ; 27 import java.util.Iterator ; 28 import java.util.List ; 29 import java.util.Map ; 30 31 import org.ofbiz.base.util.Debug; 32 33 41 public class MapComparator implements Comparator { 42 43 public static final String module = MapComparator.class.getName(); 44 45 private List keys; 46 47 51 public MapComparator(List keys) { 52 this.keys = keys; 53 } 54 55 58 public boolean equals(Object obj) { 59 return obj.equals(this); 60 } 61 62 65 public int compare(Object obj1, Object obj2) { 66 Map map1, map2; 67 try { 68 map1 = (Map ) obj1; 69 map2 = (Map ) obj2; 70 } catch (ClassCastException e) { 71 throw new IllegalArgumentException ("Objects not from the Map interface"); 72 } 73 74 if (keys == null || keys.size() < 1) { 75 throw new IllegalArgumentException ("No sort fields defined"); 76 } 77 78 Iterator i = keys.iterator(); 79 while (i.hasNext()) { 80 Object key = i.next(); 81 boolean ascending = true; 83 84 Object o1 = null; 85 Object o2 = null; 86 87 if (key instanceof FlexibleMapAccessor) { 88 FlexibleMapAccessor fmaKey = (FlexibleMapAccessor) key; 89 ascending = fmaKey.getIsAscending(); 90 91 93 o1 = fmaKey.get(map1); 94 o2 = fmaKey.get(map2); 95 } else { 96 if (key instanceof String ) { 97 String keyStr = (String ) key; 98 if (keyStr.charAt(0) == '-') { 99 ascending = false; 100 key = keyStr.substring(1); 101 } else if (keyStr.charAt(0) == '+') { 102 ascending = true; 103 key = keyStr.substring(1); 104 } 105 } 106 107 o1 = map1.get(key); 108 o2 = map2.get(key); 109 } 110 111 if (o1 == null && o2 == null) { 112 continue; 113 } 114 115 int compareResult = 0; 116 if (o1 != null && o2 == null) { 117 compareResult = -1; 118 } 119 if (o1 == null && o2 != null) { 120 compareResult = 1; 121 } 122 123 if (compareResult == 0) { 124 try { 125 Comparable comp1 = (Comparable ) o1; 127 Comparable comp2 = (Comparable ) o2; 128 compareResult = comp1.compareTo(comp2); 129 } catch (Exception e) { 130 String errorMessage = "Error sorting list of Maps: " + e.toString(); 131 Debug.logError(e, errorMessage, module); 132 throw new RuntimeException (errorMessage); 133 } 134 } 135 136 if (compareResult != 0) { 138 if (ascending) { 139 return compareResult; 140 } else { 141 return -compareResult; 142 } 143 } 144 } 145 146 return 0; 148 } 149 } 150 | Popular Tags |