标签:col tco new 情况 soft span rri 第一个 set
在某些特殊情况,我们需要对一个对象数组或集合依照对应的属性排序;此时,我们就可以用Comparator接口处理。
上代码
TestComparaTo 类
1 package com.test.interfacetest; 2 3 public class TestComparaTo implements Comparable<TestComparaTo>{ 4 private int id; 5 private String name; 6 7 public int getId() { 8 return id; 9 } 10 11 public void setId(int id) { 12 this.id = id; 13 } 14 15 public String getName() { 16 return name; 17 } 18 19 public void setName(String name) { 20 this.name = name; 21 } 22 23 @Override 24 public int compareTo(TestComparaTo o) { 25 return Integer.compare(id, o.getId()); 26 } 27 28 }
MainClass类
1 import java.util.Arrays; 2 import java.util.Collections; 3 import java.util.List; 4 5 import com.test.interfacetest.TestComparaTo; 6 7 public class MainClass { 8 9 public static void main(String[] args) { 10 TestComparaTo testComparaTo = new TestComparaTo(); 11 testComparaTo.setId(21); 12 testComparaTo.setName("钻石王老五"); 13 14 TestComparaTo testComparaTo1 = new TestComparaTo(); 15 testComparaTo1.setId(15); 16 testComparaTo1.setName("岛市老八"); 17 18 TestComparaTo testComparaTo2 = new TestComparaTo(); 19 testComparaTo2.setId(19); 20 testComparaTo2.setName("芜湖大司马"); 21 22 23 TestComparaTo[] s = {testComparaTo,testComparaTo1,testComparaTo2}; 24 List<TestComparaTo> asList = Arrays.asList(s); 25 26 27 System.out.println("排序前集合内容:"); 28 for(TestComparaTo obj : asList) { 29 System.out.println(obj.getName()+"id为:"+obj.getId()); 30 } 31 32 System.out.println("排序前数组内容:"); 33 for(TestComparaTo obj : s) { 34 System.out.println(obj.getName()+"id为:"+obj.getId()); 35 } 36 37 38 39 Arrays.sort(s); 40 Collections.sort(asList); 41 42 System.out.println("排序后集合内容:"); 43 for(TestComparaTo obj : asList) { 44 System.out.println(obj.getName()+"id为:"+obj.getId()); 45 } 46 System.out.println("排序后数组内容:"); 47 for(TestComparaTo obj : s) { 48 System.out.println(obj.getName()+"id为:"+obj.getId()); 49 } 50 51 52 } 53 54 }
总结就是:实现comparable接口的comparaTo方法,然后数组用Array的sort方法排序,集合用collection的sort方法排序。
在Java8后,可以运用lambda表达式使得Comparator使用起来更简单
例如下面四种方法
1 //以下第一个参数a、b、c、d是TestComparaTo类的实例化对象的数组,对该数组排序 2 3 //根据TestComparaTo类的name属性排序 4 Arrays.sort(a,Comparator.comparing(TestComparaTo::getName)); 5 6 //如果name相同则根据id排序 7 Arrays.sort(b,Comparator.comparing(TestComparaTo::getName).thenComparing(TestComparaTo::getId)); 8 9 //根据name长度排序 10 Arrays.sort(c,Comparator.comparing(TestComparaTo::getName,(a,t)->Integer.compare(a.length(), t.length()))); 11 12 //根据name长度排序 显然这个比上一个更简单 13 Arrays.sort(d,Comparator.comparingInt(a -> a.getName().length()));
标签:col tco new 情况 soft span rri 第一个 set
原文地址:https://www.cnblogs.com/sukeryy/p/12378632.html