Java 使用比较器排序-降序(用户定义的类)
我想使用comparator按降序对对象进行排序Java 使用比较器排序-降序(用户定义的类),java,Java,我想使用comparator按降序对对象进行排序 class Person { private int age; } 这里我想对Person对象数组进行排序 我怎样才能做到这一点呢?String[]s={“a”,“x”,“y”}; String[] s = {"a", "x", "y"}; Arrays.sort(s, new Comparator<String>() { @Override public int compare(String o1, Strin
class Person {
private int age;
}
这里我想对Person对象数组进行排序
我怎样才能做到这一点呢?String[]s={“a”,“x”,“y”};
String[] s = {"a", "x", "y"};
Arrays.sort(s, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
System.out.println(Arrays.toString(s));
-> [y, x, a]
sort,新的比较器(){
@凌驾
公共整数比较(字符串o1、字符串o2){
返回o2.compareTo(o1);
}
});
System.out.println(Arrays.toString);
->[y,x,a]
现在必须为Person类实现比较器。
类似于(升序):比较(人a,人b)=a.id
或Integer.valueOf(a.id).compareTo(Integer.valueOf(b.id))
为了尽量减少混淆,您应该实现一个升序比较器,并使用包装器()将其转换为降序比较器()new reversecomprator(new personcomprator())
s类有一个排序方法,该方法接受一个列表和一个自定义值。您可以定义自己的比较器,以根据自己的喜好对Person对象进行排序。package com.test;
package com.test;
import java.util.Arrays;
public class Person implements Comparable {
private int age;
private Person(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Object o) {
Person other = (Person)o;
if (this == other)
return 0;
if (this.age < other.age) return 1;
else if (this.age == other.age) return 0;
else return -1;
}
public static void main(String[] args) {
Person[] arr = new Person[4];
arr[0] = new Person(50);
arr[1] = new Person(20);
arr[2] = new Person(10);
arr[3] = new Person(90);
Arrays.sort(arr);
for (int i=0; i < arr.length; i++ ) {
System.out.println(arr[i].age);
}
}
}
导入java.util.array;
公共类人员实现可比性{
私人互联网;
私人(国际年龄){
超级();
这个。年龄=年龄;
}
公共整数getAge(){
回归年龄;
}
公共无效设置(整数){
这个。年龄=年龄;
}
@凌驾
公共整数比较对象(对象o){
其他人=(人)o;
if(this==其他)
返回0;
if(this.age
这里有一种方法。我将为person类创建一个比较器,可以通过某种排序行为对其进行参数化。在这里,我可以设置排序顺序,但也可以修改它以允许对其他人员属性进行排序
public class PersonComparator implements Comparator<Person> {
public enum SortOrder {ASCENDING, DESCENDING}
private SortOrder sortOrder;
public PersonComparator(SortOrder sortOrder) {
this.sortOrder = sortOrder;
}
@Override
public int compare(Person person1, Person person2) {
Integer age1 = person1.getAge();
Integer age2 = person2.getAge();
int compare = Math.signum(age1.compareTo(age2));
if (sortOrder == ASCENDING) {
return compare;
} else {
return compare * (-1);
}
}
}
公共类PersonComparator实现Comparator{
公共枚举排序器{升序,降序}
私人分拣员;
公共人员比较者(排序器排序器){
this.sortOrder=sortOrder;
}
@凌驾
公共整数比较(个人1,个人2){
整数age1=person1.getAge();
整数age2=person2.getAge();
int compare=Math.signum(年龄1.compareTo(年龄2));
if(sortOrder==升序){
返回比较;
}否则{
返回比较*(-1);
}
}
}
(希望现在可以编译,我手头没有IDE或JDK,编码为“盲”)
编辑
多亏了托马斯,编辑了代码。我不会说Math.signum的使用是好的、性能好的、有效的,但我想提醒大家,compareTo方法可以返回任何整数,如果实现返回integer.MIN\u integer,那么乘以(-1)将失败。。。我删除了setter,因为它足够便宜,可以在需要的时候构建一个新的PersonComparator
但我保留了这一点,因为它表明我依赖于现有的类似实现。可以执行类似于
Comparable age1=new Integer(person1.getAge())的操作但是那看起来太难看了。其想法是展示一种模式,这种模式可以很容易地适应其他人的属性,如姓名、生日和日期等。使用谷歌收藏:
class Person {
private int age;
public static Function<Person, Integer> GET_AGE =
new Function<Person, Integer> {
public Integer apply(Person p) { return p.age; }
};
}
public static void main(String[] args) {
ArrayList<Person> people;
// Populate the list...
Collections.sort(people, Ordering.natural().onResultOf(Person.GET_AGE).reverse());
}
班级人员{
私人互联网;
公共静态函数=
新功能{
公共整数apply(Person p){返回p.age;}
};
}
公共静态void main(字符串[]args){
ArrayList人;
//填充列表。。。
Collections.sort(people,Ordering.natural().onResultOf(Person.GET_AGE).reverse());
}
关于它的价值,这里是我的标准答案。这里唯一的新功能是使用Collections.reverseOrder()。此外,它将所有建议都放在一个示例中:
/*
** Use the Collections API to sort a List for you.
**
** When your class has a "natural" sort order you can implement
** the Comparable interface.
**
** You can use an alternate sort order when you implement
** a Comparator for your class.
*/
import java.util.*;
public class Person implements Comparable<Person>
{
String name;
int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name + " : " + age;
}
/*
** Implement the natural order for this class
*/
public int compareTo(Person p)
{
return getName().compareTo(p.getName());
}
static class AgeComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
int age1 = p1.getAge();
int age2 = p2.getAge();
if (age1 == age2)
return 0;
else if (age1 > age2)
return 1;
else
return -1;
}
}
public static void main(String[] args)
{
List<Person> people = new ArrayList<Person>();
people.add( new Person("Homer", 38) );
people.add( new Person("Marge", 35) );
people.add( new Person("Bart", 15) );
people.add( new Person("Lisa", 13) );
// Sort by natural order
Collections.sort(people);
System.out.println("Sort by Natural order");
System.out.println("\t" + people);
// Sort by reverse natural order
Collections.sort(people, Collections.reverseOrder());
System.out.println("Sort by reverse natural order");
System.out.println("\t" + people);
// Use a Comparator to sort by age
Collections.sort(people, new Person.AgeComparator());
System.out.println("Sort using Age Comparator");
System.out.println("\t" + people);
// Use a Comparator to sort by descending age
Collections.sort(people,
Collections.reverseOrder(new Person.AgeComparator()));
System.out.println("Sort using Reverse Age Comparator");
System.out.println("\t" + people);
}
}
/*
**使用Collections API为您排序列表。
**
**当类具有“自然”排序顺序时,可以实现
**可比较的界面。
**
**在实现时,可以使用备用排序顺序
**你们班的比较器。
*/
导入java.util.*;
公共类人员实现可比性
{
字符串名;
智力年龄;
公众人物(字符串名称,整数年龄)
{
this.name=名称;
这个。年龄=年龄;
}
公共字符串getName()
{
返回名称;
}
公共整数getAge()
{
回归年龄;
}
公共字符串toString()
{
返回姓名+“:”+年龄;
}
/*
**实现该类的自然顺序
*/
公共内部比较(p人)
{
返回getName().compareTo(p.getName());
}
静态类AgeComparator实现了Comparator
{
公共整数比较(人员p1、人员p2)
{
int age1=p1.getAge();
int age2=p2.getAge();
如果(年龄1==2岁)
返回0;
否则,如果(年龄1>年龄2)
返回1;
其他的
返回-1;
}
}
公共静态void main(字符串[]args)
{
List people=new ArrayList();
添加(新人物(“荷马”,38));
添加(新人物(“Marge”,35));
添加(新人物(“Bart”,15));
添加(新人物(“Lisa”,13));
//按自然顺序排序
收藏。分类(人);
System.out.println(“按自然顺序排序”);
System.out.println(“\t”+人);
//按逆自然顺序排序
Collections.sort(人,Collections.reverseOrder());
System.out.println(“按反向自然顺序排序”);
System.out.println(“\t”+人);
//使用比较器按年龄排序
Collections.sort(people,newperson.AgeComparator());
System.out.println(“使用年龄进行排序
Collections.sort(unsortedList,new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return b.getName().compareTo(a.getName());
}
});
Collections.sort(unsortedList,new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
});
Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));
personList.sort((a,b)->b.getName().compareTo(a.getName()));