比较器 Comparator

master
30980 2 years ago
parent 11e0e3ff01
commit 729101d055

@ -26,6 +26,12 @@
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
@ -63,5 +69,15 @@
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,59 @@
package com.never.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class ComparatorDemo {
public static void main(String[] args) {
Student s1 = new Student(4, 17, "张三");
Student s2 = new Student(1, 17, "张三");
Student s3 = new Student(3, 17, "张三");
Student s4 = new Student(8, 17, "张三");
Student s5 = new Student(6, 17, "张三");
System.out.println("--------Array------------");
Student[] arr = {s1,s2,s3,s4,s5};
for(int i = 0 ;i <arr.length; i++){
System.out.println(arr[i]);
}
System.out.println("--------------------");
Arrays.sort(arr,new IdComparator());
for(int i = 0 ;i <arr.length; i++){
System.out.println(arr[i]);
}
System.out.println("------ArrayList-------------");
ArrayList<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
for(Student s: list){
System.out.println(s);
}
System.out.println("--------------------");
list.sort(new IdComparator());
for(Student s: list){
System.out.println(s);
}
}
}
class IdComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
int res = 0;
if(o1.getId()<o2.getId()){
res = -1;
}else if (o1.getId()>o2.getId()){
res = 1;
}
else if (o1.getId() == o2.getId()){
res = 0;
}
return res;
}
}

@ -0,0 +1,22 @@
package com.never.basic;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Student {
private Integer id;
private Integer age;
private String name;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
Loading…
Cancel
Save