public static void main(String[] args) { Long t = System.currentTimeMillis(); Random random = new Random(); List<Apple> list = new ArrayList<Apple>(); for (int j = 0; j < 1000000; j++) { Apple a = new Apple("Apple"+1,random.nextInt(1000000)); list.add(a); } Long t2 = System.currentTimeMillis(); System.out.println(t2-t); //以下四种排序方式,任意打开一个 // list.sort(java.util.Comparator.comparing(Apple::getWeight)); list.sort((Apple a1, Apple a2) -> a1.getWeight()-a2.getWeight() ); // Collections.sort(list, new Comparator<Apple>() { // public int compare(Apple o1, Apple o2) { // return o2.getWeight()-o1.getWeight(); // } // }); // for(int j = 0; j < list.size(); j++){ // for(int m = j+1; m < list.size(); m++){ // Apple a2 = list.get(j); // if(a2.getWeight()>list.get(m).getWeight()){ // Apple am = list.get(m); // am.setWeight(a2.getWeight()); // a2.setWeight(am.getWeight()); // } // } // } for (int j = 0; j < 1000000; j++) { Apple a = list.get(j); //打印验证是否排序成功开关 //System.out.println(a.getWeight()); } Long t3 = System.currentTimeMillis(); System.out.println(t3-t2); }
结论:不管数据量的多少,用Collections.sort,远优于另外两个,数据量少(万以下,没细测)用冒泡优于Comparator.comparing,数据量最大,冒泡越耗时,综合结论,sort 优于 comparing 优于 冒泡