0
点赞
收藏
分享

微信扫一扫

Java对List的排序

覃榜言 2022-01-28 阅读 86


Java中对List排序的实现

一.实例

1.方法1:实现Comparable接口
import grammar.TestIntValue;

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

public class JavaTest {

public static int initValue = 8;
public static void main(String[] args) {
Student s3 = new Student(3, "hadoop");
Student s1 = new Student(1, "java");
Student s2 = new Student(2, "spark");
List<Student> students = new ArrayList<Student>();
students.add(s3);
students.add(s1);
students.add(s2);
System.out.println("Before:");
for(Student s : students){
System.out.println(s.toString());
}
Collections.sort(students);
System.out.println("After:");
for(Student s : students){
System.out.println(s.toString());
}
}

static class Student implements Comparable<Student>{
private int id;
private String name;

public Student(int id ,String name){
this.id = id;
this.name = name;
}

@Override
public int compareTo(Student stu) {
return this.id - stu.id;
}

@Override
public String toString() {
return "id: "+this.id+",name: "+this.name;
}
}
}
  • 实现结果
Before:
id: 3,name: hadoop
id: 1,name: java
id: 2,name: spark
After:
id: 1,name: java
id: 2,name: spark
id: 3,name: hadoop
2.匿名内部类



举报

相关推荐

0 条评论