当前位置:   article > 正文

对list中的对象进行排序_list对象排序

list对象排序

list的排序分为两大类:

一种是针对简单的包装类型进行排序,即list中存放的String或者Integer类型

另一种是针对自定义的对象类型进行排序,对象需要像包装类型一样去实现Comparable接口,然后重写CompareTo方法

一、针对简单包装类型进行排序

  1. package com.hungteshun;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. /**
  6. * @author hungteshun
  7. * @description: 对String类型、Integer类型进行排序
  8. * @date 2018/11/29 16:45
  9. */
  10. public class EasySort {
  11. public static void main(String[] args) {
  12. List<String> stringList = new ArrayList<>();
  13. stringList.add("张三");
  14. stringList.add("李四");
  15. stringList.add("王五");
  16. stringList.add("赵六");
  17. System.out.println("排序之前的顺序:" + stringList );
  18. Collections.sort(stringList);
  19. System.out.println("排序之后的顺序:" + stringList );
  20. /**
  21. * 注意这个reserve方法,是反转,而不是在无序的前提下直接倒序
  22. */
  23. Collections.reverse(stringList);
  24. System.out.println("反转之后的顺序:" + stringList );
  25. List<Integer> integerList = new ArrayList<>();
  26. integerList.add(2);
  27. integerList.add(1);
  28. integerList.add(9);
  29. integerList.add(5);
  30. integerList.add(12);
  31. integerList.add(20);
  32. System.out.println("排序之前的顺序" + integerList);
  33. Collections.sort(integerList);
  34. System.out.println("排序之后的顺序" + integerList);
  35. /**
  36. * 注意这个reserve方法,是反转,而不是在无序的前提下直接倒序
  37. */
  38. Collections.reverse(integerList);
  39. System.out.println("反转之后的顺序:" + integerList );
  40. }
  41. }

输出结果如下:

  1. 排序之前的顺序:[张三, 李四, 王五, 赵六]
  2. 排序之后的顺序:[张三, 李四, 王五, 赵六]
  3. 反转之后的顺序:[赵六, 王五, 李四, 张三]
  4. 排序之前的顺序[2, 1, 9, 5, 12, 20]
  5. 排序之后的顺序[1, 2, 5, 9, 12, 20]
  6. 反转之后的顺序:[20, 12, 9, 5, 2, 1]

查看String类的源代码,String类也实现了Comparable<String>接口,查看其重写的compareTo()方法源码:

  1. public int compareTo(String anotherString) {
  2. int len1 = value.length;
  3. int len2 = anotherString.value.length;
  4. int lim = Math.min(len1, len2);
  5. char v1[] = value;
  6. char v2[] = anotherString.value;
  7. int k = 0;
  8. while (k < lim) {
  9. char c1 = v1[k];
  10. char c2 = v2[k];
  11. if (c1 != c2) {
  12. return c1 - c2;
  13. }
  14. k++;
  15. }
  16. return len1 - len2;
  17. }

二、针对list中的对象按照某个属性进行排序

2.1、对象实现Comparable接口

新建对象的时候需要实现Comparable接口,然后重写CompareTo方法。

创建一个Student对象:

  1. package com.hungteshun.domain;
  2. /**
  3. * @author hungteshun
  4. * @description:
  5. * @date 2018/11/29 19:58
  6. */
  7. public class Student implements Comparable<Student> {
  8. private Integer age;
  9. private Integer score;
  10. private String name;
  11. public Student() {
  12. }
  13. public Student(Integer age, Integer score, String name) {
  14. this.age = age;
  15. this.score = score;
  16. this.name = name;
  17. }
  18. public Integer getAge() {
  19. return age;
  20. }
  21. public void setAge(Integer age) {
  22. this.age = age;
  23. }
  24. public Integer getScore() {
  25. return score;
  26. }
  27. public void setScore(Integer score) {
  28. this.score = score;
  29. }
  30. public String getName() {
  31. return name;
  32. }
  33. public void setName(String name) {
  34. this.name = name;
  35. }
  36. @Override
  37. public int compareTo(Student o) {
  38. //先按照年龄排序
  39. Integer i = this.age.compareTo(o.getAge());
  40. if (i == 0) {
  41. //如果年龄相等,则按照分数排序
  42. i = this.score.compareTo(o.getScore());
  43. if (i == 0) {
  44. //如果分数相等,则按照姓名排序
  45. i = this.getName().compareTo(o.getName());
  46. }
  47. }
  48. /**
  49. * i等于0的时候表示相等;
  50. * i等于1的时候表示大于;
  51. * i等于-1的时候表示小于;
  52. */
  53. return i;
  54. }
  55. @Override
  56. public String toString() {
  57. return "Student{" +
  58. "age=" + age +
  59. ", score=" + score +
  60. ", name='" + name + '\'' +
  61. '}';
  62. }
  63. }

查看一下Integer类的compareTo()方法的实现源码:

  1. public int compareTo(Integer anotherInteger) {
  2. return compare(this.value, anotherInteger.value);
  3. }

继续查看compare()方法:

  1. public static int compare(int x, int y) {
  2. return (x < y) ? -1 : ((x == y) ? 0 : 1);
  3. }

* i等于-1的时候表示小于;
* i等于0的时候表示相等;
* i等于1的时候表示大于;

对该对象的集合进行排序

  1. package com.hungteshun;
  2. import com.hungteshun.domain.Student;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. /**
  8. * @author hungteshun
  9. * @description:
  10. * @date 2018/11/29 19:56
  11. */
  12. public class StudentSort {
  13. public static void main(String[] args) {
  14. List<Student> studentList = new ArrayList<>();
  15. studentList.add(new Student(23, 90, "张三"));
  16. studentList.add(new Student(22, 97, "李四"));
  17. studentList.add(new Student(23, 95, "王五"));
  18. studentList.add(new Student(24, 91, "赵六"));
  19. studentList.add(new Student(21, 98, "赵六"));
  20. studentList.add(new Student(21, 98, "赵五"));
  21. studentList.add(new Student(21, 98, "赵七"));
  22. System.out.println("排序之前的list:");
  23. studentList.stream().forEach(System.out::println);
  24. //Collections.sort(studentList);
  25. //System.out.println("排序之后的list:");
  26. //studentList.stream().forEach(System.out::println);
  27. //使用lambda表达式的sort是一样的效果
  28. System.out.println("使用lambda表达式排序之后的list:");
  29. studentList.stream().sorted().forEach(System.out::println);
  30. }
  31. }

输出结果:

  1. 排序之前的list:
  2. Student{age=23, score=90, name='张三'}
  3. Student{age=22, score=97, name='李四'}
  4. Student{age=23, score=95, name='王五'}
  5. Student{age=24, score=91, name='赵六'}
  6. Student{age=21, score=98, name='赵六'}
  7. Student{age=21, score=98, name='赵五'}
  8. Student{age=21, score=98, name='赵七'}
  9. 使用lambda表达式排序之后的list:
  10. Student{age=21, score=98, name='赵七'}
  11. Student{age=21, score=98, name='赵五'}
  12. Student{age=21, score=98, name='赵六'}
  13. Student{age=22, score=97, name='李四'}
  14. Student{age=23, score=90, name='张三'}
  15. Student{age=23, score=95, name='王五'}
  16. Student{age=24, score=91, name='赵六'}

2.2、使用Comparator接口

Studen对象不用实现Comparable接口

  1. package com.hungteshun.domain;
  2. /**
  3. * @author hungteshun
  4. * @description:
  5. * @date 2018/11/29 19:58
  6. */
  7. public class Student {
  8. private Integer age;
  9. private Integer score;
  10. private String name;
  11. public Student() {
  12. }
  13. public Student(Integer age, Integer score, String name) {
  14. this.age = age;
  15. this.score = score;
  16. this.name = name;
  17. }
  18. public Integer getAge() {
  19. return age;
  20. }
  21. public void setAge(Integer age) {
  22. this.age = age;
  23. }
  24. public Integer getScore() {
  25. return score;
  26. }
  27. public void setScore(Integer score) {
  28. this.score = score;
  29. }
  30. public String getName() {
  31. return name;
  32. }
  33. public void setName(String name) {
  34. this.name = name;
  35. }
  36. @Override
  37. public String toString() {
  38. return "Student{" +
  39. "age=" + age +
  40. ", score=" + score +
  41. ", name='" + name + '\'' +
  42. '}';
  43. }
  44. }

对该对象的集合进行排序

  1. package com.hungteshun;
  2. import com.hungteshun.domain.Student;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. /**
  8. * @author hungteshun
  9. * @description:
  10. * @date 2018/11/29 19:56
  11. */
  12. public class StudentSort {
  13. public static void main(String[] args) {
  14. List<Student> studentList = new ArrayList<>();
  15. studentList.add(new Student(23, 90, "张三"));
  16. studentList.add(new Student(22, 97, "李四"));
  17. studentList.add(new Student(23, 95, "王五"));
  18. studentList.add(new Student(24, 91, "赵六"));
  19. studentList.add(new Student(21, 98, "赵六"));
  20. studentList.add(new Student(21, 98, "赵五"));
  21. studentList.add(new Student(21, 98, "赵七"));
  22. System.out.println("排序之前的list:");
  23. studentList.stream().forEach(System.out::println);
  24. Collections.sort(studentList, (o1, o2) -> {
  25. //先按照年龄排序
  26. Integer i = o1.getAge().compareTo(o2.getAge());
  27. if (i == 0) {
  28. //如果年龄相等,则按照分数排序
  29. i = o1.getScore().compareTo(o2.getScore());
  30. if (i == 0) {
  31. //如果分数相等,则按照姓名排序
  32. i = o1.getName().compareTo(o2.getName());
  33. }
  34. }
  35. return i;
  36. });
  37. System.out.println("排序之后的list:");
  38. studentList.stream().forEach(System.out::println);
  39. //只按照年龄排序方式一:
  40. Collections.sort(studentList, (e1, e2) -> e1.getAge().compareTo(e2.getAge()));
  41. //只按照年龄排序方式二:
  42. Collections.sort(studentList, Comparator.comparingInt(Student::getAge));
  43. System.out.println("只按照年龄排序之后的list:");
  44. studentList.stream().forEach(System.out::println);
  45. //只按照姓名排序方式一:
  46. Collections.sort(studentList, (e1, e2) -> e1.getName().compareTo(e2.getName()));
  47. //只按照姓名排序方式二:
  48. Collections.sort(studentList, Comparator.comparing(Student::getName));
  49. //只按照姓名排序方式三:
  50. Collections.sort(studentList, Comparator.comparing(e -> e.getName()));
  51. //只按照姓名排序方式四:
  52. studentList.sort((e1, e2) -> e1.getName().compareTo(e2.getName()));
  53. //只按照姓名排序方式五:
  54. studentList.sort(Comparator.comparing(Student::getName));
  55. //只按照姓名排序方式六:
  56. studentList.sort(Comparator.comparing(e -> e.getName()));
  57. }
  58. }

输出结果:

  1. 排序之前的list:
  2. Student{age=23, score=90, name='张三'}
  3. Student{age=22, score=97, name='李四'}
  4. Student{age=23, score=95, name='王五'}
  5. Student{age=24, score=91, name='赵六'}
  6. Student{age=21, score=98, name='赵六'}
  7. Student{age=21, score=98, name='赵五'}
  8. Student{age=21, score=98, name='赵七'}
  9. 排序之后的list:
  10. Student{age=21, score=98, name='赵七'}
  11. Student{age=21, score=98, name='赵五'}
  12. Student{age=21, score=98, name='赵六'}
  13. Student{age=22, score=97, name='李四'}
  14. Student{age=23, score=90, name='张三'}
  15. Student{age=23, score=95, name='王五'}
  16. Student{age=24, score=91, name='赵六'}
  17. 只按照年龄排序之后的list:
  18. Student{age=21, score=98, name='赵七'}
  19. Student{age=21, score=98, name='赵五'}
  20. Student{age=21, score=98, name='赵六'}
  21. Student{age=22, score=97, name='李四'}
  22. Student{age=23, score=90, name='张三'}
  23. Student{age=23, score=95, name='王五'}
  24. Student{age=24, score=91, name='赵六'}
  25. 只按照姓名排序之后的list:
  26. Student{age=23, score=90, name='张三'}
  27. Student{age=22, score=97, name='李四'}
  28. Student{age=23, score=95, name='王五'}
  29. Student{age=21, score=98, name='赵七'}
  30. Student{age=21, score=98, name='赵五'}
  31. Student{age=21, score=98, name='赵六'}
  32. Student{age=24, score=91, name='赵六'}

三、使用泛型对任何属性进行排序

定义一个UserInfo对象

  1. package com.hungteshun.entity;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import lombok.Getter;
  5. import lombok.Setter;
  6. import lombok.ToString;
  7. /**
  8. * @author hungteshun
  9. * @description:
  10. * @date 2018/11/31 22:21
  11. */
  12. @Getter
  13. @Setter
  14. @ToString
  15. public class UserInfo {
  16. private Long userId;
  17. private String userName;
  18. private String password;
  19. private Date birthday;
  20. private Integer sex;
  21. private Integer age;
  22. public String getBirthdayStr(){
  23. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  24. return sdf.format(getBirthday());
  25. }
  26. }

然后创建一个工具类

  1. package com.hungteshun.util;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. import org.apache.commons.lang.StringUtils;
  8. /**
  9. * @author hungteshun
  10. * @description:
  11. * @date 2018/11/31 22:23
  12. */
  13. public class SortListUtil<E> {
  14. public void Sort(List<E> list, final String method, final String order) {
  15. Collections.sort(list, new Comparator<E>() {
  16. @Override
  17. public int compare(E o1, E o2) {
  18. int ret = 0;
  19. try {
  20. Method method1 = o1.getClass().getMethod(method, null);
  21. Method method2 = o2.getClass().getMethod(method, null);
  22. //倒序
  23. if (StringUtils.isNotEmpty(order) && "desc".equalsIgnoreCase(order)) {
  24. ret = method2.invoke(o2, null).toString().compareTo(method1.invoke(o1, null)
  25. .toString());
  26. }
  27. else {
  28. ret = method1.invoke(o1, null).toString()
  29. .compareTo(method2.invoke(o2, null).toString());
  30. }
  31. } catch (NoSuchMethodException e) {
  32. e.printStackTrace();
  33. } catch (IllegalAccessException e) {
  34. e.printStackTrace();
  35. } catch (InvocationTargetException e) {
  36. e.printStackTrace();
  37. }
  38. return ret;
  39. }
  40. });
  41. }
  42. }

主方法中调用

  1. package com.hungteshun;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.ArrayList;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import com.hungteshun.entity.UserInfo;
  8. import com.hungteshun.util.SortListUtil;
  9. /**
  10. * @author hungteshun
  11. * @description:
  12. * @date 2018/11/31 22:15:30
  13. */
  14. public class App {
  15. public static void main(String[] args) throws ParseException {
  16. List<UserInfo> userInfos = new ArrayList<>();
  17. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  18. UserInfo userInfo = new UserInfo();
  19. userInfo.setUserId(2L);
  20. userInfo.setUserName("b");
  21. userInfo.setAge(10);
  22. userInfo.setBirthday(format.parse("2000-10-01"));
  23. userInfos.add(userInfo);
  24. userInfo = new UserInfo();
  25. userInfo.setUserId(1L);
  26. userInfo.setUserName("c");
  27. userInfo.setAge(30);
  28. userInfo.setBirthday(format.parse("1980-10-01"));
  29. userInfos.add(userInfo);
  30. userInfo = new UserInfo();
  31. userInfo.setUserId(3L);
  32. userInfo.setUserName("a");
  33. userInfo.setAge(20);
  34. userInfo.setBirthday(format.parse("1990-10-01"));
  35. userInfos.add(userInfo);
  36. SortListUtil<UserInfo> sortList = new SortListUtil<UserInfo>();
  37. System.out.println("==========原来的顺序==========");
  38. for (Iterator<UserInfo> iterator = userInfos.iterator(); iterator.hasNext(); ) {
  39. UserInfo userInfo1 = iterator.next();
  40. System.out.println(userInfo1);
  41. }
  42. System.out.println("==========按照userId排序==========");
  43. sortList.Sort(userInfos, "getUserId", null);
  44. for (Iterator<UserInfo> iterator = userInfos.iterator(); iterator.hasNext(); ) {
  45. UserInfo userInfo1 = iterator.next();
  46. System.out.println(userInfo1);
  47. }
  48. System.out.println("==========按照userName倒序排序==========");
  49. sortList.Sort(userInfos, "getUserName", "desc");
  50. for (Iterator<UserInfo> iterator = userInfos.iterator(); iterator.hasNext(); ) {
  51. UserInfo userInfo1 = iterator.next();
  52. System.out.println(userInfo1);
  53. }
  54. //这里按照日期排序是默认按照星期进行排序,因此我们需要对返回的日期格式进行手动格式化成yyyy-MM-dd类型
  55. System.out.println("==========按照birthday排序==========");
  56. sortList.Sort(userInfos, "getBirthday", null);
  57. for (Iterator<UserInfo> iterator = userInfos.iterator(); iterator.hasNext(); ) {
  58. UserInfo userInfo1 = iterator.next();
  59. System.out.println(userInfo1);
  60. }
  61. System.out.println("==========按照birthdayStr排序==========");
  62. sortList.Sort(userInfos, "getBirthdayStr", null);
  63. for (UserInfo userInfo1 : userInfos) {
  64. System.out.println(userInfo1);
  65. }
  66. }
  67. }

 

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号