List怎么自定义排序

方式一,集合里面的元素实现Comparable接口

sort方法要求集合元素必须实现Comparable 接口,该接口用于规定实现类是可以比较的。 其有一个抽象方法是用来定义比较大小的规则。我们想使用sort方法排序集合,但是该方法要求我们的集合元素必须实现Comparable接口并且定义比较规则,这种我们想使用某个功能,而它要求我们修改程序的现象称为“侵入性”。修改的代码越多,侵入性越强,越不利于程序的扩展。

当实现了Comparable接口后,需要重写下面的方法该方法的作用是定义当前对象与给定参数对象比较大小 的规则。
返回值为一个int值,该值表示大小关系。它不关注具
体的返回值>0时:当前对象比参数对象大
当前返回值<0时:当前对象比参数对象小
当前返回=0时:两个对象相等。

package day05;
/**
 * 该类用于作为集合的元素
 * @author lenovo
 *
 */
public class Point implements Comparable<Point>{
	public Point(int x,int y){
		this.x = x;
		this.y = y;
	}
	private int x;
	private int y;
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	public String toString(){
		return "("+x+","+y+")";
	}
	@Override
	/**
	 * 当实现了Comparable接口后,需要重写下面的方法
	 * 该方法的作用是定义当前对象与给定参数对象比较大小
	 * 的规则。
	 * 返回值为一个int值,该值表示大小关系。它不关注具
	 * 体的返回值>0时:当前对象比参数对象大
	 * 当前返回值<0时:当前对象比参数对象小
	 * 当前返回=0时:两个对象相等。
	 */
	public int compareTo(Point o) {
		/*
		 * 比较规则,点到原点的距离长的大
		 */
		int len = this.x*this.x+this.y*this.y;
		int olen = o.x*o.x+o.y*o.y;
		return len-olen;
	}
       
	
	
}
package day05;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 排序自定义类型元素的集合
 * @author lenovo
 *
 */
public class SortListDemo1 {
	public static void main(String[] args){
		List<Point> list = new ArrayList<Point>();
		list.add(new Point(4,2));
		list.add(new Point(2,3));
		list.add(new Point(1,4));
		list.add(new Point(6,7));
		list.add(new Point(9,3));
		list.add(new Point(8,1));
		
		System.out.println(list);
		/*
		 * sort方法要求集合元素必须实现Comparable
		 * 接口,该接口用于规定实现类是可以比较的。
		 * 其有一个抽象方法是用来定义比较大小的规则。
		 * 
		 * 我们想使用sort方法排序集合,但是该方法要求
		 * 我们的集合元素必须实现Comparable接口并且
		 * 定义比较规则,这种我们想使用某个功能,而它
		 * 要求我们修改程序的现象称为“侵入性”。
		 * 修改的代码越多,侵入性越强,越不利于程序
		 * 的扩展。
		 */
		Collections.sort(list);
		
		System.out.println(list);
		
	}
}

第二种使用匿名内部类或者自定义一个类实现Comparator接口(推荐使用匿名内部类)

 重载的sort方法要求传入一个额外的比较器该方法不再要求集合元素必须实现Comparable接口,并且也不再使用集合元素自身的比较规则排序了,而是根据给定的这个额外的比较器的比较 规则对集合元素进行排序。实际开发中也推荐使用这种方式排序集合元素,若集合元素是自定义的。创建比较器时也推荐使用匿名内部类的形式。

package day05;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortListDemo2 {
	public static void main(String[] args) {
		List<Point> list = new ArrayList<Point>();
		list.add(new Point(4,2));
		list.add(new Point(2,3));
		list.add(new Point(1,4));
		list.add(new Point(6,7));
		list.add(new Point(9,3));
		list.add(new Point(8,1));
		
		System.out.println(list);
		//Comparator<String> com = new MyComparator();
		/*
		 * 重载的sort方法要求传入一个额外的比较器
		 * 该方法不再要求集合元素必须实现Comparable
		 * 接口,并且也不再使用集合元素自身的比较规则
		 * 排序了,而是根据给定的这个额外的比较器的比较
		 * 规则对集合元素进行排序。
		 * 实际开发中也推荐使用这种方式排序集合元素,若
		 * 集合元素是自定义的。
		 * 创建比较器时也推荐使用匿名内部类的形式。
		 */
		
		
		//匿名内部类形式创建
		Comparator<Point> com1 = new Comparator<Point>(){

			@Override
			public int compare(Point o1, Point o2) {
				// TODO Auto-generated method stub
				return (o1.getX()*o1.getY())-(o2.getX()*o2.getY());
			}

			
		};
		
		Collections.sort(list,com1);
		System.out.println(list);
		
	}
}
/**
 * 定义一个额外的比较器
 */
class MyComparator implements Comparator<Point>{
	@Override
	public int compare(Point o1, Point o2) {
		// TODO Auto-generated method stub
		return (o1.getX()*o1.getY())-(o2.getX()*o2.getY());
	}
}

 

### Java 8 List 自定义排序示例 在 Java 8 中,`List` 的自定义排序可以通过 `Collections.sort()` 方法或者流式 API (`Stream`) 来实现。以下是两种方法的具体说明: #### 使用 `Collections.sort()` 进行自定义排序 可以利用 `Comparator` 接口来创建一个比较器,并将其传递给 `Collections.sort()` 方法以完成自定义排序。 ```java import java.util.*; class Employee { private int id; private String name; private int age; public Employee(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Employee{id=" + id + ", name='" + name + "', age=" + age + "}"; } } public class CustomSortExample { public static void main(String[] args) { List<Employee> employees = new ArrayList<>(); employees.add(new Employee(3, "Alice", 29)); employees.add(new Employee(1, "Bob", 24)); employees.add(new Employee(2, "Charlie", 35)); // 按照年龄升序排列 Collections.sort(employees, Comparator.comparing(Employee::getAge)); System.out.println("按年龄升序排序:"); employees.forEach(System.out::println); // 按照名字降序排列 Collections.sort(employees, Comparator.comparing(Employee::getName).reversed()); System.out.println("\n按名字降序排序:"); employees.forEach(System.out::println); } } ``` 上述代码展示了如何基于对象的不同属性进行排序[^2]。 --- #### 使用 Stream 和 `sorted()` 方法进行自定义排序 Java 8 提供了更简洁的方式——通过流式操作来进行排序。下面是一个例子,展示如何按照员工的 ID 升序和降序排序。 ```java import java.util.*; import java.util.stream.Collectors; public class StreamCustomSortExample { public static void main(String[] args) { List<Employee> employees = Arrays.asList( new Employee(3, "Alice", 29), new Employee(1, "Bob", 24), new Employee(2, "Charlie", 35) ); // 按照ID升序排列 List<Employee> sortedByIdAsc = employees.stream() .sorted(Comparator.comparing(Employee::getId)) .collect(Collectors.toList()); System.out.println("按ID升序排序:"); sortedByIdAsc.forEach(System.out::println); // 按照ID降序排列 List<Employee> sortedByIdDesc = employees.stream() .sorted(Comparator.comparing(Employee::getId).reversed()) .collect(Collectors.toList()); System.out.println("\n按ID降序排序:"); sortedByIdDesc.forEach(System.out::println); } } ``` 这段代码演示了如何使用 `stream().sorted()` 方法对列表中的元素进行升序或降序排序[^3]。 --- #### 总结 无论是使用传统的 `Collections.sort()` 方法还是现代的流式 API,都可以轻松实现针对复杂对象的多维度排序需求。开发者可以根据实际场景选择适合的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值