亲宝软件园·资讯

展开

Java List自定义排序 Java怎样实现List自定义排序

崔笑颜 人气:0
想了解Java怎样实现List自定义排序的相关内容吗,崔笑颜在本文为您仔细讲解Java List自定义排序的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,List自定义排序,Java,自定义排序,Java,list,下面大家一起来学习吧。

实体类

package com.whty.entity;

public class User {
	private int id;
	private String name;
	private int age;
	
	public User(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 String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}

测试类

package com.whty.test;

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

import com.whty.entity.User;

public class Test {
	public static void main(String[] args) {
		List<User> list = new ArrayList<>();
		list.add(new User(1, "java", 20));
		list.add(new User(2, "spark", 19));
		list.add(new User(3, "hive", 21));
		
		for(User user :list) {
			System.out.println("排序前:" + user.toString());
		}
		//实现排序
		Collections.sort(list, new Comparator<User>() {
			@Override
			public int compare(User u1, User u2) {
				if(u1.getAge() > u2.getAge()) {
					//return -1:即为正序排序
					return -1;
				}else if (u1.getAge() == u2.getAge()) {
					return 0;
				}else {
					//return 1: 即为倒序排序
					return 1;
				}
			}
		});
		
		for(User user :list) {
			System.out.println("排序后:" + user.toString());
		}
	}
}

运行结果

排序前:User [id=1, name=java, age=20]
排序前:User [id=2, name=spark, age=19]
排序前:User [id=3, name=hive, age=21]
排序后:User [id=3, name=hive, age=21]
排序后:User [id=1, name=java, age=20]
排序后:User [id=2, name=spark, age=19]

加载全部内容

相关教程
猜你喜欢
用户评论