org.apache.commons.collections.ComparatorUtils Java Examples

The following examples show how to use org.apache.commons.collections.ComparatorUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExcelUtil.java    From jframework with Apache License 2.0 6 votes vote down vote up
private static void sortByProperties(List<? extends Object> list, boolean isNullHigh,
                                     boolean isReversed, String... props) {
    if (CollectionUtils.isNotEmpty(list)) {
        Comparator<?> typeComp = ComparableComparator.getInstance();
        if (isNullHigh == true) {
            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);
        }
    }
}
 
Example #2
Source File: MyBeanUtils.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 根据给定的条件,把 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);
}
 
Example #3
Source File: ActionListAction.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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++);
    }
}
 
Example #4
Source File: FunUtil.java    From youkefu with Apache License 2.0 5 votes vote down vote up
/**
* 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);
}
 
Example #5
Source File: ReleaseChannelMap.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #6
Source File: GithubServerContainer.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Iterator<ScmServerEndpoint> iterator() {
    List<Endpoint> endpoints = Ordering.from(new Comparator<Endpoint>() {
        @Override
        public int compare(Endpoint o1, Endpoint o2) {
            return ComparatorUtils.NATURAL_COMPARATOR.compare(o1.getName(), o2.getName());
        }
    }).sortedCopy(GitHubConfiguration.get().getEndpoints());
    return Iterators.transform(endpoints.iterator(), new Function<Endpoint, ScmServerEndpoint>() {
        @Override
        public ScmServerEndpoint apply(Endpoint input) {
            return new GithubServer(input, getLink());
        }
    });
}
 
Example #7
Source File: ArrayUtilsTest.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testArgmaxTArrayComparatorOfQsuperT() {
    Double[] a = new Double[] {2d, 5d, 0d, null, 1d};
    Assert.assertEquals(2, argmax(a, ComparatorUtils.nullLowComparator(
        ComparatorUtils.reversedComparator(ComparatorUtils.naturalComparator()))));
    Assert.assertEquals(1,
        argmax(a, ComparatorUtils.nullLowComparator(ComparatorUtils.naturalComparator())));
    Assert.assertEquals(3,
        argmax(a, ComparatorUtils.nullHighComparator(ComparatorUtils.naturalComparator())));
}
 
Example #8
Source File: Repository.java    From webdriverextensions-maven-plugin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static List<Driver> sortDrivers(List<Driver> drivers) {
    Comparator byId = new ArgumentComparator(on(Driver.class).getId());
    Comparator byVersion = new ArgumentComparator(on(Driver.class).getVersion());
    Comparator orderByIdAndVersion = ComparatorUtils.chainedComparator(byId, byVersion);

    return sort(drivers, on(Driver.class), orderByIdAndVersion);
}
 
Example #9
Source File: ReleaseChannelMap.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #10
Source File: ApacheCloudStackApiCommandParameter.java    From apache-cloudstack-java-client with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public int compareTo(ApacheCloudStackApiCommandParameter o) {
    return ComparatorUtils.NATURAL_COMPARATOR.compare(this.name, o.name);
}
 
Example #11
Source File: RegExRelationshipAnnotator.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected void extract(JCas jCas) throws AnalysisEngineProcessException {

  Map<String, Entity> idMap = new HashMap<>();

  JCasUtil.select(jCas, sourceType).forEach(e -> idMap.put(toEntityIdentifier(e, sourceType), e));
  if (!targetType.equals(sourceType)) {
    JCasUtil.select(jCas, targetType)
        .forEach(e -> idMap.put(toEntityIdentifier(e, targetType), e));
  }

  StringBuilder builder = new StringBuilder();
  String documentText = jCas.getDocumentText();

  List<Entry<String, Entity>> sorted =
      (List<Entry<String, Entity>>)
          idMap.entrySet().stream()
              .sorted(
                  Entry.comparingByValue(
                      ComparatorUtils.reversedComparator(Comparator.comparing(Entity::getBegin))))
              .collect(Collectors.toList());

  int processedTo = documentText.length();
  for (Entry<String, Entity> entry : sorted) {
    String id = entry.getKey();
    Entity entity = entry.getValue();
    int entityBegin = entity.getBegin();
    int entityEnd = entity.getEnd();
    if (entityEnd > processedTo) {
      continue; // Ignore overlapping entities
    }

    builder.insert(0, documentText.substring(entityEnd, processedTo));
    builder.insert(0, id);
    processedTo = entityBegin;
  }

  builder.insert(0, documentText.substring(0, processedTo));

  String substitutedText = builder.toString();

  Matcher m = p.matcher(substitutedText);
  while (m.find()) {
    String sourceString = m.group(sourceGroup);
    String targetString = m.group(targetGroup);

    Entity source = idMap.get(sourceString);
    Entity target = idMap.get(targetString);

    String sourceValue = Optional.ofNullable(source.getValue()).orElse("");
    String targetValue = Optional.ofNullable(target.getValue()).orElse("");

    String value =
        Optional.ofNullable(m.group(valueGroup))
            .map(s -> s.replace(sourceString, sourceValue).replace(targetString, targetValue))
            .orElse("");

    int begin = Math.min(source.getBegin(), target.getBegin());
    int end = Math.max(source.getEnd(), target.getEnd());

    addToJCasIndex(createRelation(jCas, source, target, begin, end, value));
  }
}