/** * 根据给定的条件,把 list 中的 javabean 排序。 * 用到了 commons beanutils 和 commons.collections * * @param list 待排序的 list * @param listOrderedMap 排序条件。 * 这是一个有序的 list ,排序条件按照加入到 list 的 bean 的属性(map 的 key)的先后顺序排序。 * listOrderedMap 的 key 为待排序的 bean 的属性名称,值为是否按该属性的正序排序,true 为正序,false 为逆序。 * 使用方法见本类的 testSortListBeans() 方法例子,使用时注意不要写错 bean 的属性名称。 * @param <T> list 中的 bean 类型 */ public static <T> void sortListBeans(List<T> list, ListOrderedMap listOrderedMap) { int num = listOrderedMap.size(); ArrayList sortFields = new ArrayList(); for (int i = 0; i < num; i++) { // System.out.println("key =" + listOrderedMap.get(i) + " , value=" + listOrderedMap.getValue(i)); Comparator comp = ComparableComparator.getInstance(); comp = ComparatorUtils.nullLowComparator(comp); //允许null if ((Boolean) listOrderedMap.getValue(i) == false) comp = ComparatorUtils.reversedComparator(comp); //逆序 Comparator cmp = new BeanComparator((String) listOrderedMap.get(i), comp); sortFields.add(cmp); } ComparatorChain multiSort = new ComparatorChain(sortFields); Collections.sort(list, multiSort); }
private void sortActionList(List<? extends ActionItemBase> actionList, String sortName, SortOrderEnum sortOrder) { if (StringUtils.isEmpty(sortName)) { return; } Comparator<ActionItemBase> comparator = new ActionItemComparator(sortName); if (SortOrderEnum.DESCENDING.equals(sortOrder)) { comparator = ComparatorUtils.reversedComparator(comparator); } Collections.sort(actionList, comparator); // re-index the action items int index = 0; for (ActionItemBase actionItem : actionList) { actionItem.setActionListIndex(index++); } }
private void attachRoutesForClass(Router router, Class<? extends ServerResource> clazz) { TreeSet<String> pathsOrderedByLength = new TreeSet<String>(ComparatorUtils.chainedComparator(new Comparator<String>() { private IntComparator _intComparator = IntComparators.NATURAL_COMPARATOR; @Override public int compare(String o1, String o2) { return _intComparator.compare(o1.length(), o2.length()); } }, ComparatorUtils.NATURAL_COMPARATOR)); for (Method method : clazz.getDeclaredMethods()) { Annotation annotationInstance = method.getAnnotation(Paths.class); if (annotationInstance != null) { pathsOrderedByLength.addAll(Arrays.asList(((Paths) annotationInstance).value())); } } for (String routePath : pathsOrderedByLength) { LOGGER.info("Attaching route {} -> {}", routePath, clazz.getSimpleName()); router.attach(routePath, new AddHeaderFilter(getContext(), createFinder(clazz))); } }
/** * Kmeansクラスタリングのデータをマージする。<br> * 以下の順でマージを実施する。<br> * <ol> * <li>ベース中心点配列とマージ対象中心点配列の各々のユークリッド距離を算出する。(中心点がn個あった場合nの二乗個のユークリッド距離が算出される)</li> * <li>nの二乗個のユークリッド距離のうち、値が小さいものからベース中心点、マージ対象中心点のマッピングを行う。その際、既に使用されている中心点はマッピングに使用しない。</li> * <li>マッピングした中心点同士を用いて中心点のマージを行う。</li> * </ol> * * @param baseKmeans マージ元Kmeansクラスタリング * @param targetKmeans マージ対象Kmeansクラスタリング * @return マージ後のクラスタリングデータ */ public static final KmeansDataSet mergeKmeans(KmeansDataSet baseKmeans, KmeansDataSet targetKmeans) { KmeansDataSet merged = new KmeansDataSet(); int centroidNum = (int) ComparatorUtils.min(baseKmeans.getCentroids().length, targetKmeans.getCentroids().length, ComparatorUtils.NATURAL_COMPARATOR); // ベース中心点配列とマージ対象中心点配列の各々のユークリッド距離を算出 List<CentroidMapping> allDistance = calculateDistances(baseKmeans.getCentroids(), targetKmeans.getCentroids(), centroidNum); // nの二乗個のユークリッド距離のうち、値が小さいものからベース中心点、マージ対象中心点のマッピングを生成する Collections.sort(allDistance, new CentroidsComparator()); Map<Integer, Integer> resultMapping = createCentroidMappings(centroidNum, allDistance); // マッピングを用いて中心点をマージ double[][] mergedCentroids = mergeCentroids(baseKmeans.getCentroids(), targetKmeans.getCentroids(), resultMapping); merged.setCentroids(mergedCentroids); return merged; }
@SuppressWarnings("unchecked") public static void sortByProperties(List<? extends Object> list, boolean isNullHigh, boolean isReversed, String... props) { if (CollectionUtils.isNotEmpty(list)) { Comparator<?> typeComp = ComparableComparator.getInstance(); if (isNullHigh) { typeComp = ComparatorUtils.nullHighComparator(typeComp); } else { typeComp = ComparatorUtils.nullLowComparator(typeComp); } if (isReversed) { typeComp = ComparatorUtils.reversedComparator(typeComp); } List<Object> sortCols = new ArrayList<Object>(); if (props != null) { for (String prop : props) { sortCols.add(new BeanComparator(prop, typeComp)); } } if (sortCols.size() > 0) { Comparator<Object> sortChain = new ComparatorChain(sortCols); Collections.sort(list, sortChain); } } }
@SuppressWarnings("unchecked") // unchecked cast private Comparator<?> getComparator(ExtendedProperties properties, String keyPreffix) { String key = keyPreffix + ".comparator"; String[] classNames = properties.getStringArray(key); List<Comparator<?>> comparators = new ArrayList<>(); Comparator<?> c; for (String name : classNames) { c = getComparator(name); if (c != null) { comparators.add(c); } } return comparators.isEmpty() ? null : (Comparator<?>) ComparatorUtils.chainedComparator(comparators); // unchecked cast }
@SuppressWarnings("unchecked") // unchecked cast public static <T> Collection<T> sort(Collection<T> collection, Comparator<T>... comparators) { if (collection instanceof List && !collection.isEmpty() && comparators != null) { List<T> list = (List<T>) collection; Comparator<T> comparator = (Comparator<T>) ComparatorUtils.chainedComparator(comparators); // unchecked cast Collections.sort(list, comparator); } return collection; }
@Test public void testSortingByMultipleColumn() { Comparator<User> byAge = new ArgumentComparator<User, Integer>(on(User.class).getAge()); Comparator<User> byRegistYmdt = new ArgumentComparator<User, Date>(on(User.class).getRegistYmdt()); @SuppressWarnings("unchecked") Comparator<User> orderBy = ComparatorUtils.chainedComparator(byAge, byRegistYmdt); List<User> sortedList = sort(userList, on(User.class), orderBy); println("Test sorting:", sortedList); }
/** * Partial Sort: sorts in place an array of Objects using a given Comparator, * but only enough so that the N biggest (or smallest) items are at the start * of the array. Not a stable sort, unless the Comparator is so contrived. * * @param items will be partially-sorted in place * @param comp a Comparator; null means use natural comparison */ static <T> void partialSort(T[] items, Comparator<T> comp, int limit) { if (comp == null) { //noinspection unchecked comp = (Comparator<T>) ComparatorUtils.naturalComparator(); } new Quicksorter<T>(items, comp).partialSort(limit); }
@SuppressWarnings({"unchecked"}) private void doPartialSort(Object[] items, boolean descending, int limit) { Comparator<Object> comp = ComparatorUtils.naturalComparator(); if (descending) { comp = ComparatorUtils.reversedComparator(comp); } FunUtil.partialSort(items, comp, limit); }
private static <T extends Comparable> boolean isPartiallySorted( T [] vec, int limit, boolean descending) { //noinspection unchecked return isPartiallySorted( vec, limit, (Comparator<T>) ComparatorUtils.naturalComparator(), descending); }
/** * basePointのtargetPointに関する到達可能距離(Reachability distance)を算出する。 * * @param basePoint 算出元対象点 * @param targetPoint 算出先対象点 * @return 到達可能距離 */ protected static double calculateReachDistance(LofPoint basePoint, LofPoint targetPoint) { double distance = MathUtils.distance(basePoint.getDataPoint(), targetPoint.getDataPoint()); double reachDistance = (double) ComparatorUtils.max(distance, targetPoint.getkDistance(), ComparatorUtils.NATURAL_COMPARATOR); return reachDistance; }
/** * compare to ReleaseChannelMap * @param o the other object * @return the compare return */ public int compareTo(ReleaseChannelMap o) { List<Comparator> compar = new ArrayList<Comparator>(); compar.add(new DynamicComparator("channel", true)); compar.add(new DynamicComparator("channelArch", true)); compar.add(new DynamicComparator("product", true)); compar.add(new DynamicComparator("version", true)); compar.add(new DynamicComparator("release", true)); Comparator com = ComparatorUtils.chainedComparator( (Comparator[]) compar.toArray()); return com.compare(this, o); }
private void doPartialSort(Object[] items, boolean descending, int limit) { Comparator comp = ComparatorUtils.naturalComparator(); if (descending) { comp = ComparatorUtils.reversedComparator(comp); } FunUtil.partialSort(items, comp, limit); }
private void speedTest(int length, int limit) { System.out.println( "sorting the max " + limit + " of " + length + " random Integers"); // random input, 3 copies // repeated keys Integer[] vec1 = newRandomIntegers(length, 0, length / 5); Integer[] vec2 = new Integer[length]; Integer[] vec3 = new Integer[length]; System.arraycopy(vec1, 0, vec2, 0, length); System.arraycopy(vec1, 0, vec3, 0, length); // full sort vec1 long now = System.currentTimeMillis(); Arrays.sort(vec1); long dt = System.currentTimeMillis() - now; System.out.println(" full mergesort took " + dt + " msecs"); // partial sort vec2 now = System.currentTimeMillis(); doPartialSort(vec2, true, limit); dt = System.currentTimeMillis() - now; System.out.println(" partial quicksort took " + dt + " msecs"); // stable partial sort vec3 Comparator comp = new ReverseComparator(ComparatorUtils.naturalComparator()); List<Integer> vec3List = Arrays.asList(vec3); now = System.currentTimeMillis(); FunUtil.stablePartialSort(vec3List, comp, limit); dt = System.currentTimeMillis() - now; System.out.println(" stable partial quicksort took " + dt + " msecs"); }
private void sortActionList(List<? extends ActionItemActionListExtension> actionList, String sortName, SortOrderEnum sortOrder) { if (StringUtils.isEmpty(sortName)) { return; } Comparator<ActionItemActionListExtension> comparator = new ActionItemComparator(sortName); if (SortOrderEnum.DESCENDING.equals(sortOrder)) { comparator = ComparatorUtils.reversedComparator(comparator); } Collections.sort(actionList, comparator); // re-index the action items int index = 0; for (ActionItemActionListExtension actionItem : actionList) { actionItem.setActionListIndex(index++); } }
@Override @SuppressWarnings("unchecked") public int compareTo(ApacheCloudStackApiCommandParameter o) { return ComparatorUtils.NATURAL_COMPARATOR.compare(this.name, o.name); }
private void speedTest(Logger logger, int length, int limit) { logger.debug( "sorting the max " + limit + " of " + length + " random Integers"); // random input, 3 copies // repeated keys Integer[] vec1 = newRandomIntegers(length, 0, length / 5); Integer[] vec2 = vec1.clone(); Integer[] vec3 = vec1.clone(); Integer[] vec4 = vec1.clone(); // full sort vec1 long now = System.currentTimeMillis(); Arrays.sort(vec1); long dt = System.currentTimeMillis() - now; logger.debug(" full mergesort took " + dt + " msecs"); // partial sort vec2 now = System.currentTimeMillis(); doPartialSort(vec2, true, limit); dt = System.currentTimeMillis() - now; logger.debug(" partial quicksort took " + dt + " msecs"); // marc's stable partial quicksort vec3 @SuppressWarnings({"unchecked"}) Comparator<Integer> comp = new ReverseComparator(ComparatorUtils.naturalComparator()); List<Integer> vec3List = Arrays.asList(vec3); now = System.currentTimeMillis(); FunUtil.stablePartialSort(vec3List, comp, limit, 2); dt = System.currentTimeMillis() - now; logger.debug(" marc's stable partial quicksort took " + dt + " msecs"); // julian's algorithm stable partial sort vec4 @SuppressWarnings({"unchecked"}) List<Integer> vec4List = Arrays.asList(vec4); now = System.currentTimeMillis(); FunUtil.stablePartialSort(vec4List, comp, limit, 4); dt = System.currentTimeMillis() - now; logger.debug(" julian's stable partial sort took " + dt + " msecs"); }
private static <T extends Comparable> boolean isPartiallySorted( T [] vec, int limit, boolean descending) { return isPartiallySorted( vec, limit, ComparatorUtils.naturalComparator(), descending); }
/** * Partial Sort: sorts in place an array of Objects using a given Comparator, * but only enough so that the N biggest (or smallest) items are at the start * of the array. Not a stable sort, unless the Comparator is so contrived. * * @param items will be partially-sorted in place * @param comp a Comparator; null means use natural comparison * @param limit */ static void partialSort(Object[] items, Comparator comp, int limit) { if (comp == null) { comp = ComparatorUtils.naturalComparator(); } new Quicksorter(items, comp).partialSort(limit); }