/** * Constructs a property-based comparator for beans. This constructor creates a BeanComparator * that uses the supplied Comparator to compare the property values. * * @param property Name of a bean property, can contain the name of a simple, nested, indexed, * mapped, or combined property. See {@link PropertyUtilsBean} for property query language * syntax. * @param comparator BeanComparator will pass the values of the specified bean property to this * Comparator. If your bean property is not a comparable or contains null values, a suitable * comparator may be supplied in this constructor. */ public BeanComparator(String property, Comparator comparator) { setProperty(property); if (comparator != null) { this.comparator = comparator; } else { this.comparator = ComparableComparator.getInstance(); } }
@SuppressWarnings({"unchecked", "rawtypes"}) public static void main(String[] args) { List<User> list = new ArrayList<User>(); list.add(new User(2, "姚郁", 28)); list.add(new User(1, "孟志昂", 25)); list.add(new User(3, "矿宗义", 30)); list.add(new User(4, "王仕强", 25)); System.out.println("-----排序前-----"); for (User u : list) { System.out.println(u.name + "/" + u.age); } System.out.println("-----满足:先按age升序排列,再按id降序排列-----"); List sortFields = new ArrayList(); Comparator mycmp = ComparableComparator.getInstance(); mycmp = ComparatorUtils.reversedComparator(mycmp); sortFields.add(new BeanComparator("age")); sortFields.add(new BeanComparator("id", mycmp)); ComparatorChain multiSort = new ComparatorChain(sortFields); Collections.sort(list, multiSort); for (User u : list) { System.out.println(u.id + "/" + u.name + "/" + u.age); } }
/** * Constructs a property-based comparator for beans. This compares two beans by the property * specified in the property parameter. This constructor creates a <code>BeanComparator</code> * that uses a <code>ComparableComparator</code> to compare the property values. * * <p>Passing "null" to this constructor will cause the BeanComparator to compare objects based on * natural order, that is <code>java.lang.Comparable</code>. * * @param property String Name of a bean property, which may contain the name of a simple, nested, * indexed, mapped, or combined property. See {@link PropertyUtilsBean} for property query * language syntax. If the property passed in is null then the actual objects will be compared */ public BeanComparator(String property) { this(property, ComparableComparator.getInstance()); }