在上面的类中,我们在构造器中初始化了一个 ArrayList 对象。在 sortAscending()方法中,我们调用了 Collections.sort()方法,并传递这个初始化的 ArrayList对象为参数,返回排序后的 ArrayList。在 sortDescending()方法中,我们调用重载的 Collections.sort()方法让其按照降序对元素排序,这个版本的 Collections.sort()接收ArrayList对象作为第一个参数,一个由 Collections.reverseOrder()方法返回的 Comparator 对象作为第二个参数。我们将会在稍后讲解 Comparator。为了测试排序功能,我们将写一段测试代码。package guru.springframework.blog.sortarraylist.ascendingdescending;
import java.util.ArrayList;
import java.util.Collections;
public class SortArrayListAscendingDescending {
private ArrayList arrayList;
public SortArrayListAscendingDescending(ArrayList arrayList) {
this.arrayList = arrayList;
}
public ArrayList getArrayList() {
return this.arrayList;
}
public ArrayList sortAscending() {
Collections.sort(this.arrayList);
return this.arrayList;
}
public ArrayList sortDescending() {
Collections.sort(this.arrayList, Collections.reverseOrder());
return this.arrayList;
}
}
在上面的测试代码中,我们创建一个 ArrayList 对象,并添加了 5 个字符串对象代表 5 个国家的名字。然后我们调用 getArrayList()、sortAscending()和 sortDescending()方法,并打印这些方法返回的 ArrayList 对象。package guru.springframework.blog.sortarraylist.ascendingdescending;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class SortArrayListAscendingDescendingTest {
<a href="http://www.jobbole.com/members/madao">@Test</a>
public void testSortAscendingDescending() throws Exception {
ArrayList countryList = new ArrayList<>();
countryList.add("France");
countryList.add("USA");
countryList.add("India");
countryList.add("Spain");
countryList.add("England");
SortArrayListAscendingDescending sortArrayList = new SortArrayListAscendingDescending(countryList);
ArrayList unsortedArrayList = sortArrayList.getArrayList();
System.out.println("Unsorted ArrayList: " + unsortedArrayList);
ArrayList sortedArrayListAscending = sortArrayList.sortAscending();
System.out.println("Sorted ArrayList in Ascending Order : " + sortedArrayListAscending);
ArrayList sortedArrayListDescending = sortArrayList.sortDescending();
System.out.println("Sorted ArrayList in Descending Order: " + sortedArrayListDescending);
}
}
在上面 JobCandidate 类被重写的 compareTo()方法中,我们实现了基于年龄的比较逻辑。我见过很多程序员将(this.getAge() – candidate.getAge())作为返回的比较结果。尽管使用这种 return 语句看上去似乎很吸引人,并且也不会对我们的例子造成影响,我的建议是远离这种语句。想象一下,比较整数值,其中有一个或者两个都是负数的结果。这会导致一些错误,让你的程序行为不定,而且更重要的是,这样的错误是很细微的,尤其是在大型的企业应用中很难检测出来。下面我们将写一个辅助类,为委托方对包含了 JobCandidate 元素的 ArrayList 对象进行排序。package guru.springframework.blog.sortarraylist.comparable;
public class JobCandidate implements Comparable {
private String name;
private String gender;
private int age;
public JobCandidate(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
@Override
public int compareTo(JobCandidate candidate) {
return (this.getAge() < candidate.getAge() ? -1 :
(this.getAge() == candidate.getAge() ? 0 : 1));
}
@Override
public String toString() {
return " Name: " + this.name + ", Gender: " + this.gender + ", age:" + this.age;
}
}
在 JobCandidateSorter 类中,我们初始化了一个 ArrayList 对象,委托方将通过构造函数实例化 JobCandidateSorter 。然后我们编写了 getSortedJobCandidateByAge()方法,在这个方法中,我们调用 Collections.sort()并传递已经初始化了的 ArrayList 为参数,最后返回排序后的 ArrayList。package guru.springframework.blog.sortarraylist.comparable;
import java.util.ArrayList;
import java.util.Collections;
public class JobCandidateSorter {
ArrayList jobCandidate = new ArrayList<>();
public JobCandidateSorter(ArrayList jobCandidate) {
this.jobCandidate = jobCandidate;
}
public ArrayList getSortedJobCandidateByAge() {
Collections.sort(jobCandidate);
return jobCandidate;
}
}
在上面的测试类中,我们创建了四个 JobCandidate 对象并把它们添加到 ArrayList,然后传递这个 ArrayList 到构造函数来实例化 JobCandidateSorter 类。最后,我们调用 JobCandidateSorter 类的 getSortedJobCandidateByAge()方法,并打印这个方法返回的排序后的 ArrayList。测试的输出结果如下:package guru.springframework.blog.sortarraylist.comparable;
import org.junit.Test;
import java.lang.reflect.Array;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class JobCandidateSorterTest {
<a href="http://www.jobbole.com/members/madao">@Test</a>
public void testGetSortedJobCandidateByAge() throws Exception {
JobCandidate jobCandidate1 = new JobCandidate("Mark Smith", "Male", 26);
JobCandidate jobCandidate2 = new JobCandidate("Sandy Hunt", "Female", 23);
JobCandidate jobCandidate3 = new JobCandidate("Betty Clark", "Female", 20);
JobCandidate jobCandidate4 = new JobCandidate("Andrew Styne", "Male", 24);
ArrayList jobCandidateList = new ArrayList<>();
jobCandidateList.add(jobCandidate1);
jobCandidateList.add(jobCandidate2);
jobCandidateList.add(jobCandidate3);
jobCandidateList.add(jobCandidate4);
JobCandidateSorter jobCandidateSorter = new JobCandidateSorter(jobCandidateList);
ArrayList sortedJobCandidate = jobCandidateSorter.getSortedJobCandidateByAge();
System.out.println("-----Sorted JobCandidate by age: Ascending-----");
for (JobCandidate jobCandidate : sortedJobCandidate) {
System.out.println(jobCandidate);
}
}
}
在上面的类中,从 29 行到 35 行,我们写了一个匿名类并实现了 compare()方法,按照年龄的降序对 JobCandidate 对象进行排序。从37行到42行,我们又写了一个匿名类并实现了 compare() 方法,按照姓名的升序对 JobCandidate进行排序。现在我们写一个类,为委托方对 ArrayList 的元素进行排序。package guru.springframework.blog.sortarraylist.comparator;
import java.util.Comparator;
public class JobCandidate {
private String name;
private String gender;
private int age;
public JobCandidate(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
public static Comparator ageComparator = new Comparator() {
@Override
public int compare(JobCandidate jc1, JobCandidate jc2) {
return (jc2.getAge() < jc1.getAge() ? -1 :
(jc2.getAge() == jc1.getAge() ? 0 : 1));
}
};
public static Comparator nameComparator = new Comparator() {
@Override
public int compare(JobCandidate jc1, JobCandidate jc2) {
return (int) (jc1.getName().compareTo(jc2.getName()));
}
};
@Override
public String toString() {
return " Name: " + this.name + ", Gender: " + this.gender + ", age:" + this.age;
}
}
在上面的类中,我们写了 getSortedJobCandidateByAge()方法,在这个方法内部我们调用了 Collections.sort()的重载版本,这个版本传递要被排序的 ArrayList 对象和比较年龄的 Comparator 对象。在 getSortedJobCandidateByName()方法内部,我们又调用了 Collections.sort()的另一个重载版本,这个版本传递要被排序的 ArrayList 对象和比较姓名的 Comparator 对象。package guru.springframework.blog.sortarraylist.comparator;
import java.util.ArrayList;
import java.util.Collections;
public class JobCandidateSorter {
ArrayList jobCandidate = new ArrayList<>();
public JobCandidateSorter(ArrayList jobCandidate) {
this.jobCandidate = jobCandidate;
}
public ArrayList getSortedJobCandidateByAge() {
Collections.sort(jobCandidate, JobCandidate.ageComparator);
return jobCandidate;
}
public ArrayList getSortedJobCandidateByName() {
Collections.sort(jobCandidate, JobCandidate.nameComparator);
return jobCandidate;
}
}
在测试类中我们向 ArrayList 中添加若干 JobCandidate 对象,并使用 Before 注释在测试单元的 setup()方法中创建了一个 JobCandidateSorter 对象。如果你是一个 Junit 新手,可以参考我以前的文章包括 Junit 注释(Junit 单元测试系列)。在 testGetSortedJobCandidateByAge()测试方法中我们调用了 getSortedJobCandidateByAge()方法,并打印了该方法返回的排序后的 ArrayList。在 testGetSortedJobCandidateByName()测试方法中我们调用了getSortedJobCandidateByName()方法并同样打印该方法返回的 ArrayList。测试的输出如下:package guru.springframework.blog.sortarraylist.comparator;
import guru.springframework.blog.sortarraylist.comparator.JobCandidate;
import guru.springframework.blog.sortarraylist.comparator.JobCandidateSorter;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class JobCandidateSorterTest {
JobCandidateSorter jobCandidateSorter;
@Before
public void setUp() throws Exception {
JobCandidate jobCandidate1 = new JobCandidate("Mark Smith", "Male", 26);
JobCandidate jobCandidate2 = new JobCandidate("Sandy Hunt", "Female", 23);
JobCandidate jobCandidate3 = new JobCandidate("Betty Clark", "Female", 20);
JobCandidate jobCandidate4 = new JobCandidate("Andrew Styne", "Male", 24);
ArrayList jobCandidateList = new ArrayList<>();
jobCandidateList.add(jobCandidate1);
jobCandidateList.add(jobCandidate2);
jobCandidateList.add(jobCandidate3);
jobCandidateList.add(jobCandidate4);
jobCandidateSorter = new JobCandidateSorter(jobCandidateList);
}
<a href="http://www.jobbole.com/members/madao">@Test</a>
public void testGetSortedJobCandidateByAge() throws Exception {
System.out.println("-----Sorted JobCandidate by age: Descending-----");
ArrayList sortedJobCandidate = jobCandidateSorter.getSortedJobCandidateByAge();
for (JobCandidate jobCandidate : sortedJobCandidate) {
System.out.println(jobCandidate);
}
}
<a href="http://www.jobbole.com/members/madao">@Test</a>
public void testGetSortedJobCandidateByName() throws Exception {
System.out.println("-----Sorted JobCandidate by name: Ascending-----");
ArrayList sortedJobCandidate = jobCandidateSorter.getSortedJobCandidateByName();
for (JobCandidate jobCandidate : sortedJobCandidate) {
System.out.println(jobCandidate);
}
}
}
package com.yonyou.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
Student zlj = new Student("丁晓宇", 21);
Student dxy = new Student("赵四", 22);
Student cjc = new Student("张三", 11);
Student lgc = new Student("刘武", 19);
List<Student> studentList = new ArrayList<Student>();
studentList.add(zlj);
studentList.add(dxy);
studentList.add(cjc);
studentList.add(lgc);
System.out.println("按照年齡排序:");
Collections.sort(studentList, new SortByAge());
for (Student student : studentList) {
System.out.println(student.getName() + " / " + student.getAge());
}
System.out.println(" ========= ");
System.out.println("按照姓名排序");
Collections.sort(studentList, new SortByName());
for (Student student : studentList) {
System.out.println(student.getName() + " / " + student.getAge());
}
}
}
class SortByAge implements Comparator {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if (s1.getAge() > s2.getAge())
return 1;
else if (s1.getAge() == s2.getAge()) {
return 0;
}
return -1;
}
}
class SortByName implements Comparator {
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if(s1.getName().compareTo(s2.getName()) < 0)
return -1;
else if (s1.getName().compareTo(s2.getName()) > 0) {
return 1;
}
return 0;
}
}
class Student{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String name,int age) {
this.age = age;
this.name = name;
}
}
package com.lj.test;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("hello");
arrayList.add("hello");
arrayList.add("hello");
arrayList.add("world");
arrayList.add("world");
arrayList.add("java");
ArrayList<String> arrayListnew = new ArrayList<>();
for(String s:arrayList){
if(!arrayListnew.contains(s)){
arrayListnew.add(s);
//便利旧集合没有就添加到新集合
}
}
System.out.println("arraylistnew:" + arrayListnew);
}
}
简单定义一个学生类,传入名字及年龄即可。需要特别注意的是由于我们要比较学生对象里面的名字及年龄是否相等才能判断该对象是否相等所以这里需要重写学生类的equals()方法,有ecplise自动生成即可package com.lj.test;
public class Student {
private String studnet;
private int age;
public Student() {
super();
}
public Student(String studnet, int age) {
super();
this.studnet = studnet;
this.age = age;
}
public String getStudnet() {
return studnet;
}
public void setStudnet(String studnet) {
this.studnet = studnet;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [studnet=" + studnet + ", age=" + age + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (studnet == null) {
if (other.studnet != null)
return false;
} else if (!studnet.equals(other.studnet))
return false;
return true;
}
}
package com.lj.test;
import java.util.ArrayList;
public class ArrayListDemo2 {
public static void main(String[] args) {
ArrayList<Student> arrayList = new ArrayList<>();
ArrayList<Student> arrayListnew = new ArrayList<>();
Student s1 = new Student("pirlo",21);
Student s2 = new Student("pirlo",21);
Student s3 = new Student("范厨师",22);
Student s4 = new Student("马师傅",21);
Student s5 = new Student("非洲德化",24);
Student s6 = new Student("pirlo",22);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
arrayList.add(s4);
arrayList.add(s5);
arrayList.add(s6);
for(Student s :arrayList){
System.out.println(s);
if(!arrayListnew.contains(s)){
arrayListnew.add(s);
}
}
System.out.println("---------------------");
for(Student s:arrayListnew){
System.out.println(s);
}
}
}
package com.lj.test;
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListDemo3 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("adobe");
arrayList.add("piack");
arrayList.add("锤子");
arrayList.add("手");
arrayList.add("下面是中文");
arrayList.add("我是中文");
arrayList.add("上面是中文加1");
arrayList.add("敖厂长");
arrayList.add("王尼玛");
arrayList.add("back");
arrayList.add("aeobe");
Collections.sort(arrayList);
System.out.println(arrayList);
}
}
package com.lj.test;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
super();
}
public Student(String studnet, int age) {
super();
this.name = studnet;
this.age = age;
}
public String getStudnet() {
return name;
}
public void setStudnet(String studnet) {
this.name = studnet;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [studnet=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Student o) {
int num = this.age - o.age;
int num2 = num == 0 ?this.name.compareTo(o.name):num;
return num2;
}
}
运行结果:package com.lj.test;
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListDemo3 {
public static void main(String[] args) {
ArrayList<Student> arrayList = new ArrayList<Student>();
Student s1 = new Student("pirlo",21);
Student s3 = new Student("范厨师",23);
Student s4 = new Student("马师傅",21);
Student s5 = new Student("非洲德化",24);
Student s6 = new Student("pirlo",22);
arrayList.add(s1);
arrayList.add(s3);
arrayList.add(s4);
arrayList.add(s5);
arrayList.add(s6);
Collections.sort(arrayList);
for(Student s : arrayList){
System.out.println(s);
}
}
}
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛