org.apache.commons.collections.comparators.ComparableComparator Java Examples

The following examples show how to use org.apache.commons.collections.comparators.ComparableComparator. 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: 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 #2
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 #3
Source File: AggregationGroupByTrimmingService.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Sorter getSorter(int trimSize, AggregationFunction aggregationFunction, boolean isComparable) {
  // This will cover both MIN and MINMV
  boolean minOrder = aggregationFunction instanceof MinAggregationFunction;

  if (isComparable) {
    if (minOrder) {
      return new ComparableSorter(trimSize, Collections.reverseOrder());
    } else {
      return new ComparableSorter(trimSize, new ComparableComparator());
    }
  } else {
    // Reverse the comparator so that keys are ordered in descending order
    if (minOrder) {
      return new NonComparableSorter(trimSize, new ComparableComparator(), aggregationFunction);
    } else {
      return new NonComparableSorter(trimSize, Collections.reverseOrder(), aggregationFunction);
    }
  }
}
 
Example #4
Source File: ActionListUtil.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
  * Converts a collection of Recipients into a collection of WebFriendlyRecipients which can be displayed in the UI
  * @param recipients recipients to convert
  * @return a collection of WebFriendlyRecipients which can be displayed in the UI
  */
 public static List<WebFriendlyRecipient> getWebFriendlyRecipients(Collection<Recipient> recipients) {
     Collection<WebFriendlyRecipient> newRecipients = new ArrayList<WebFriendlyRecipient>(recipients.size());
     for (Recipient recipient : recipients) {
         newRecipients.add(new WebFriendlyRecipient(recipient));
     }
     List<WebFriendlyRecipient> recipientList = new ArrayList<WebFriendlyRecipient>(newRecipients);
     Collections.sort(recipientList, new Comparator<WebFriendlyRecipient>() {
         Comparator<String> comp = new ComparableComparator();

         @Override
public int compare(WebFriendlyRecipient o1, WebFriendlyRecipient o2) {
             return comp.compare(o1.getDisplayName().trim().toLowerCase(), o2.getDisplayName().trim().toLowerCase());
         }
     });
     return recipientList;
 }
 
Example #5
Source File: CellComparatorHelper.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * This method returns a comparator to be used for comparing propertyValues (in String form)
 * @param propClass
 * @return
 */
public static Comparator getAppropriateValueComparatorForPropertyClass(Class propClass) {
    if (propClass == null) {
        return NullValueComparator.getInstance();
    }
    else if (TypeUtils.isDecimalClass(propClass) || TypeUtils.isIntegralClass(propClass)) {
        return NumericValueComparator.getInstance();
    }
    else if (TypeUtils.isTemporalClass(propClass)) {
        return TemporalValueComparator.getInstance();
    }
    else if (String.class.equals(propClass)) {
        // StringCellComparator is smarter about nulls than String.CASE_INSENSITIVE_ORDER
        return StringValueComparator.getInstance();
    }
    else {
        return ComparableComparator.getInstance();
    }
}
 
Example #6
Source File: CellComparatorHelper.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * This method returns a comparator to be used for comparing the contents of cells, that is
 * the compareTo method will be invoked w/ displaytag Cell objects
 * @param propClass
 * @return
 */
public static Comparator getAppropriateComparatorForPropertyClass(Class propClass) {
    // TODO, do we really need to create so many comparators (1 per each cell)?
    if (propClass == null) {
        return new NullCellComparator();
    }
    else if (TypeUtils.isDecimalClass(propClass) || TypeUtils.isIntegralClass(propClass)) {
        return new NumericCellComparator();
    }
    else if (TypeUtils.isTemporalClass(propClass)) {
        return new TemporalCellComparator();
    }
    else if (String.class.equals(propClass)) {
        // StringCellComparator is smarter about nulls than String.CASE_INSENSITIVE_ORDER
        return new StringCellComparator();
    }
    else {
        return ComparableComparator.getInstance();
    }
}
 
Example #7
Source File: TestVolatileGeneration.java    From lsmtree with Apache License 2.0 6 votes vote down vote up
public void testIterator() throws Exception {
    final File logPath = new File(tmpDir, "tmp.log");
    VolatileGeneration<Integer, Long> volatileGeneration = new VolatileGeneration(logPath, new IntSerializer(), new LongSerializer(), new ComparableComparator());
    int[] random = new int[1000000];
    Random r = new Random(0);
    for (int i = 0; i < random.length; i++) {
        random[i] = r.nextInt();
    }
    for (int element : random) {
        volatileGeneration.put(element, (long)element);
    }
    int[] sorted = new int[random.length];
    System.arraycopy(random, 0, sorted, 0, random.length);
    Arrays.sort(sorted);
    verifyIterationOrder(volatileGeneration, sorted);

    volatileGeneration.close();
    volatileGeneration = new VolatileGeneration<Integer, Long>(new File(tmpDir, "tmp2.log"), new IntSerializer(), new LongSerializer(), new ComparableComparator());
    volatileGeneration.replayTransactionLog(logPath);
    verifyIterationOrder(volatileGeneration, sorted);
}
 
Example #8
Source File: AlumniSearchDegreeProvider.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Object provide(Object source, Object currentValue) {

    AlumniMailSendToBean bean = (AlumniMailSendToBean) source;
    final List<Degree> degrees = new ArrayList<Degree>(bean.getDegreeType().getDegreeSet());
    Collections.sort(degrees, new ComparableComparator());
    return degrees;
}
 
Example #9
Source File: BeanPropertyComparator.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Constructs a PropertyComparator for comparing beans using the properties named in the given List.
 *
 * <p>Properties will be compared
 * in the order in which they are listed. Case will be ignored if ignoreCase is true.</p>
 * 
 * @param propertyNames List of property names (as Strings) used to compare beans
 * @param ignoreCase if true, case will be ignored during String comparisons
 */
public BeanPropertyComparator(List propertyNames, boolean ignoreCase) {
    if (propertyNames == null) {
        throw new IllegalArgumentException("invalid (null) propertyNames list");
    }
    if (propertyNames.size() == 0) {
        throw new IllegalArgumentException("invalid (empty) propertyNames list");
    }
    this.propertyNames = Collections.unmodifiableList(propertyNames);
    this.ignoreCase = ignoreCase;

    if (ignoreCase) {
        this.stringComparator = String.CASE_INSENSITIVE_ORDER;
    }
    else {
        this.stringComparator = ComparableComparator.getInstance();
    }
    this.booleanComparator = new Comparator() {
        public int compare(Object o1, Object o2) {
            int compared = 0;

            Boolean b1 = (Boolean) o1;
            Boolean b2 = (Boolean) o2;

            if (!b1.equals(b2)) {
                if (b1.equals(Boolean.FALSE)) {
                    compared = -1;
                }
                else {
                    compared = 1;
                }
            }

            return compared;
        }

    };
    this.genericComparator = ComparableComparator.getInstance();
}
 
Example #10
Source File: HadoopAbstractMapTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public Comparator<Object> groupComparator() {
    return ComparableComparator.getInstance();
}
 
Example #11
Source File: ImmutableBTreeIndex.java    From lsmtree with Apache License 2.0 4 votes vote down vote up
public Reader(Path path, Serializer<K> keySerializer, Serializer<V> valueSerializer, final boolean mlockFiles) throws IOException {
    this(path, new ComparableComparator(), keySerializer, valueSerializer, mlockFiles);
}
 
Example #12
Source File: HadoopAbstractMapTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public Comparator<Object> sortComparator() {
    return ComparableComparator.getInstance();
}
 
Example #13
Source File: PointInterval.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
@Override
public T getEnd() {
    Preconditions.checkArgument(!isEmpty(), "There are no points in this interval");
    return (T)Collections.max(points,ComparableComparator.getInstance());
}
 
Example #14
Source File: PointInterval.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
@Override
public T getStart() {
    Preconditions.checkArgument(!isEmpty(),"There are no points in this interval");
    return (T)Collections.min(points,ComparableComparator.getInstance());
}
 
Example #15
Source File: GraphCentricQuery.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
@Override
public Comparator<TitanElement> getSortOrder() {
    if (orders.isEmpty()) return new ComparableComparator();
    else return orders;
}
 
Example #16
Source File: MessageQueueAction.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
        * Sets up the expected state by retrieving the selected RouteQueue by RouteQueueId, and placing it in the
        * ExistingRouteQueue member.
        *
        * Called by the super's Execute method on every request.
        */
   @Override
public ActionMessages establishRequiredState(HttpServletRequest request, ActionForm form) throws Exception {
request.setAttribute("rice_constant", getServlet().getServletContext().getAttribute("RiceConstants"));
request.setAttribute("ksb_constant", getServlet().getServletContext().getAttribute("KSBConstants"));
MessageQueueForm routeQueueForm = (MessageQueueForm) form;
routeQueueForm.setMyIpAddress(RiceUtilities.getIpNumber());
routeQueueForm.setMyApplicationId(CoreConfigHelper.getApplicationId());
routeQueueForm.setMessagePersistence(ConfigContext.getCurrentContextConfig().getProperty(KSBConstants.Config.MESSAGE_PERSISTENCE));
routeQueueForm.setMessageDelivery(ConfigContext.getCurrentContextConfig().getProperty(KSBConstants.Config.MESSAGE_DELIVERY));
routeQueueForm.setMessageOff(ConfigContext.getCurrentContextConfig().getProperty(KSBConstants.Config.MESSAGING_OFF));
List<ServiceInfo> services = KsbApiServiceLocator.getServiceRegistry().getAllOnlineServices();
if (routeQueueForm.getMessageId() != null) {
    PersistedMessageBO rq = getRouteQueueService().findByRouteQueueId(routeQueueForm.getMessageId());
    if (rq != null) {
	routeQueueForm.setExistingQueueDate(RiceConstants.getDefaultDateFormat().format(new Date()));
	routeQueueForm.setMessageQueueFromDatabase(rq);
	// establish IP addresses where this message could safely be forwarded to
	String serviceName = rq.getServiceName();
	for (ServiceInfo serviceInfo : services) {
	    if (serviceInfo.getServiceName().equals(serviceName)) {
		routeQueueForm.getIpAddresses().add(
			new ConcreteKeyValue(serviceInfo.getServerIpAddress(), serviceInfo.getServerIpAddress()));
	    }
	}
    } else {
	ActionMessages messages = new ActionMessages();
	messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
		"messagequeue.RouteQueueService.queuedDocumentNotFound", routeQueueForm.getMessageId().toString()));
	return messages;
    }
    routeQueueForm.setMessageId(null);
} else if (!"clear".equalsIgnoreCase(request.getParameter("methodToCall"))) {
    List<PersistedMessageBO> queueEntries = findRouteQueues(request, routeQueueForm, routeQueueForm.getMaxRows() + 1);
    if (queueEntries.size() > 0) {
	Collections.sort(queueEntries, new Comparator() {
	    private Comparator comp = new ComparableComparator();

	    @Override
		public int compare(Object object1, Object object2) {
		if (object1 == null && object2 == null) {
		    return 0;
		} else if (object1 == null) {
		    return 1;
		} else if (object2 == null) {
		    return -1;
		}
		Long id1 = ((PersistedMessageBO) object1).getRouteQueueId();
		Long id2 = ((PersistedMessageBO) object2).getRouteQueueId();

		try {
		    return this.comp.compare(id1, id2);
		} catch (Exception e) {
		    return 0;
		}
	    }
	});
    }
    routeQueueForm.setMessageQueueRows(queueEntries);
}
return null;
   }
 
Example #17
Source File: PointInterval.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public T getEnd() {
    Preconditions.checkArgument(!isEmpty(), "There are no points in this interval");
    return (T) Collections.max(points, ComparableComparator.getInstance());
}
 
Example #18
Source File: PointInterval.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public T getStart() {
    Preconditions.checkArgument(!isEmpty(), "There are no points in this interval");
    return (T) Collections.min(points, ComparableComparator.getInstance());
}
 
Example #19
Source File: GraphCentricQuery.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Comparator<JanusGraphElement> getSortOrder() {
    if (orders.isEmpty()) return new ComparableComparator();
    else return orders;
}