有关在Java中对自定义对象进行排序的完整指南。 Collections.sort()方法基于Comparable或Comparator实现进行排序。 用于对Employee对象进行排序的示例自定义排序
1.简介
在本教程中,您将学习如何在java中对Custom对象进行排序 。 首先,我们将显示示例程序以对字符串列表进行排序,然后移至
自定义Employee的Arraylist的排序 。 排序由Empoyee完成
ID,姓名和年龄 。 本文末尾显示的所有示例均在GitHub上。
2. Collections.sort()示例
Collections类具有一个sort()方法,该方法采用List实现,例如ArrayList , LinkedList等。
现在,创建一个带有字符串值的列表,并使用Collections.sort()方法对这些值进行排序。
默认情况下,Collections.sort()方法以升序进行排序。 所有添加到列表中的值必须实现Comparable接口。
如果将null传递给sort()方法,它将抛出java.lang.NullPointerException 。
2.1字符串排序表
package com.java.w3schools.blog.collections; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /**
*
* Collections.sort() example to sort List of Strngs.
*
* @author JavaProgramTo.com
*
*/ public class CollectionSortExample {
public static void main(String[] args) {
List countries = new ArrayList<>();
countries.add( "Singapore" );
countries.add( "India" );
countries.add( "USA" );
countries.add( "UK" );
countries.add( "Australia" );
System.out.println( "List of countires before sorting : " );
Iterator it = countries.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Collections.sort(countries);
System.out.println( "List of countries after sorting :" );
it = countries.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
} }
输出:
List of countires before sorting : Singapore India USA UK Australia List of countries after sorting : Australia India Singapore UK USA
2.2整数排序列表
整数素数排序程序列表。
package com.java.w3schools.blog.collections.sorting; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /**
*
* Collections.sort() example to sort List of Strngs.
*
* @author JavaProgramTo.com
*
*/ public class CollectionSortIntegersExample {
public static void main(String[] args) {
List primeNumbers = new ArrayList<>();
primeNumbers.add( 19 );
primeNumbers.add( 7 );
primeNumbers.add( 37 );
primeNumbers.add( 59 );
primeNumbers.add( 23 );
System.out.println( "List of integer prime numnbers before sorting : " );
Iterator it = primeNumbers.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Collections.sort(primeNumbers);
System.out.println( "List of integer prime numnbers after sorting :" );
it = primeNumbers.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
} }
输出:
List of integer prime numnbers before sorting : 19 7 37 59 23 List of integer prime numnbers after sorting : 7 19 23 37 59
参见上面的两个程序,它们按从低到高的升序对整数和字符串按字母顺序进行排序。
如果传递了不同类型的对象,则将获得ClassCastException,如下所示。
public class CollectionSortClassCastException {
public static void main(String[] args) {
List values = new ArrayList();
values.add( "Singapore" );
values.add( 737 );
values.add(2323f);
Collections.sort(values);
} }
错误:
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap' )
at java.base/java.lang.Integer.compareTo(Integer.java: 64 )
at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java: 320 )
at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java: 188 )
at java.base/java.util.Arrays.sort(Arrays.java: 1316 )
at java.base/java.util.Arrays.sort(Arrays.java: 1510 )
at java.base/java.util.ArrayList.sort(ArrayList.java: 1749 )
at java.base/java.util.Collections.sort(Collections.java: 143 )
at com.java.w3schools.blog.collections.sorting.CollectionSortClassCastException.main(CollectionSortClassCastException.java: 25 )
2.3降序排列
将Comparator传递给sort()方法将按照与升序相反的顺序进行排序。 reverseOrder()方法返回一个比较器以逆转自然顺序。
Collections.sort(countries, Collections.reverseOrder()) Collections.sort(primeNumbers, Collections.reverseOrder())
3.使用员工对象的Java自定义排序
到目前为止,显示了带有Strings和Integers的示例程序。 有一种常见的方案可以对用户定义的对象进行排序,每个访问员都希望更好地了解收集概念。
我们将通过Employe类按ID排序来演示该示例。
首先,使用ID,名称和年龄创建Employee类。
接下来,实现Comparable接口并提供对compareTo()方法的实现。
package com.java.w3schools.blog.collections.sorting; public class Employee implements Comparable {
private int id;
private String name;
private int age;
public Employee( int id, String name, int age) {
super ();
this .id = id;
this .name = name;
this .age = age;
}
public int getId() {
return id;
}
public void setId( int id) {
this .id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this .name = name;
}
public int getAge() {
return age;
}
public void setAge( int age) {
this .age = age;
}
@Override
public int compareTo(Employee o) {
if (o.getId() > this .getId()) {
return 1 ;
} else if (o.getId() < this .getId()) {
return - 1 ;
}
return 0 ;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]" ;
} }
3.1按ID对Employee对象进行排序
package com.java.w3schools.blog.collections.sorting; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class CustomEmplpoyeeSortById {
public static void main(String[] args) {
List emps = new ArrayList<>();
emps.add( new Employee( 2001 , "Modi" , 55 ));
emps.add( new Employee( 1901 , "Trumph" , 57 ));
emps.add( new Employee( 1950 , "Boris Johnson" Employee( "Boris Johnson" , 56 ));
System.out.println( "Before sorting custom list of employees : " );
Iterator it = emps.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Collections.sort(emps);
System.out.println( "After sorting custom list of employees in natural order: " );
it = emps.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Collections.sort(emps, Collections.reverseOrder());
System.out.println( "After sorting custom list of employees in decendng order: " );
it = emps.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
} }
输出:
Before sorting custom list of employees : Employee [id= 2001 , name=Modi, age= 55 ] Employee [id= 1901 , name=Trumph, age= 57 ] Employee [id= 1950 , name=Boris Johnson, age= 56 ] After sorting custom list of employees in natural order: Employee [id= 2001 , name=Modi, age= 55 ] Employee [id= 1950 , name=Boris Johnson, age= 56 ] Employee [id= 1901 , name=Trumph, age= 57 ] After sorting custom list of employees in decendng order: Employee [id= 1901 , name=Trumph, age= 57 ] Employee [id= 1950 , name=Boris Johnson, age= 56 ] Employee [id= 2001 , name=Modi, age= 55 ]
3.2按名称排序Employee对象的列表
更改比较埠名称。
@Override
public int compareTo(Employee o) {
return this .getName().compareTo(o.getName()); }
现在运行生成按名称排序的程序。
Before sorting custom list of employees : Employee [id= 2001 , name=Modi, age= 55 ] Employee [id= 1901 , name=Trumph, age= 57 ] Employee [id= 1950 , name=Boris Johnson, age= 56 ] After sorting custom list of employees by name in natural order: Employee [id= 1950 , name=Boris Johnson, age= 56 ] Employee [id= 2001 , name=Modi, age= 55 ] Employee [id= 1901 , name=Trumph, age= 57 ] After sorting custom list of employees by name in decendng order: Employee [id= 1901 , name=Trumph, age= 57 ] Employee [id= 2001 , name=Modi, age= 55 ] Employee [id= 1950 , name=Boris Johnson, age= 56 ]
3.3按年龄排序员工对象列表
根据员工类别的年龄更改比较。
@Override public int compareTo(Employee o) {
if (o.getAge() > this .getAge()) {
return 1 ;
} else if (o.getAge() < this .getAge()) {
return - 1 ;
}
return 0 ; }
输出:
Before sorting custom list of employees : Employee [id= 2001 , name=Modi, age= 55 ] Employee [id= 1901 , name=Trumph, age= 57 ] Employee [id= 1950 , name=Boris Johnson, age= 56 ] After sorting custom list of employees by age in natural order: Employee [id= 1901 , name=Trumph, age= 57 ] Employee [id= 1950 , name=Boris Johnson, age= 56 ] Employee [id= 2001 , name=Modi, age= 55 ] After sorting custom list of employees by age in decendng order: Employee [id= 2001 , name=Modi, age= 55 ] Employee [id= 1950 , name=Boris Johnson, age= 56 ] Employee [id= 1901 , name=Trumph, age= 57 ]
4. Java 8自定义排序-比较器
通过在Java 8中使用lambda表达式,我们可以如下所示在单行中编写自定义比较器。
Comparator compareByName = (Employee o1, Employee o2) -> o1.getName().compareTo( o2.getName() ); Collections.sort(emps, compareByName);
上面的代码生成的输出与在第3节示例中看到的相同。
5.结论
在本文中,我们已经看到了如何在Java中对字符串和整数列表进行排序。 排序列表按升序和降序排列。 示例程序可能存在错误。
而且,基于员工ID,姓名和年龄变量的自定义排序。
GitHub代码
翻译自: https://www.javacodegeeks.com/2020/04/java-8-collections-sort-method-list-custom-sort-example-by-employe-objects-id-name-age.html