数组排序
示例1:基本类型数组排序
public static void main(String[] args) {
String[] data = {"zhangsan", "lii", "wanger","wangsan321" ,"qian321qi","maiz2i", "qianwu"};
Arrays.sort(data);
for (String item : data){
System.out.println(item);
}
System.out.println("-------内部类-------");
String[] data2 = {"zhangsan", "lii", "wanger","wangsan321" ,"qian321qi","maiz2i", "qianwu"};
class AA implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.length()-o2.length();
}
}
AA aa = new AA();
Arrays.sort(data2,aa);
for (String item : data2){
System.out.println(item);
}
System.out.println("------匿名内部类--------");
String[] data3 = {"zhangsan", "lii", "wanger","wangsan321" ,"qian321qi","maiz2i", "qianwu"};
Arrays.sort(data3, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length()- o2.length();
}
});
for (String item : data3){
System.out.println(item);
}
System.out.println("------Lambda表达式--------");
String[] data4 = {"zhangsan", "lii", "wanger","wangsan321" ,"qian321qi","maiz2i", "qianwu"};
Arrays.sort(data4,(o1,o2)->o1.length()-o2.length());
Stream.of(data4).forEach(System.out::println);
}
示例2:对象数组排序
public class Stu {
private int id;
private String name;
private float score;
public Stu() {
}
public Stu(int id, String name, float score) {
this.id = id;
this.name = name;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
@Override
public String toString() {
return "Stu{" +
"id=" + id +
", name='" + name + '\'' +
", score=" + score +
'}';
}
}
public static void main(String[] args) {
Stu zhangsan = new Stu(1001, "zhangsan", 88.8f);
Stu lisi = new Stu(1007, "lisi", 68.8f);
Stu wanger = new Stu(1005, "wanger", 98.8f);
Stu mazi = new Stu(1004, "mazi", 88.8f);
Stu qianwu = new Stu(1002, "qianwu", 78.8f);
Stu[] data1 = {zhangsan,lisi,wanger,mazi,qianwu};
Arrays.sort(data1, new Comparator<Stu>() {
@Override
public int compare(Stu o1, Stu o2) {
return o1.getId()-o2.getId();
}
});
for (Stu stu : data1) {
System.out.println(stu);
}
System.out.println("-----------------");
Stu[] data2 = {zhangsan,lisi,wanger,mazi,qianwu};
Arrays.sort(data2,(o1,o2)->o2.getName().compareTo(o1.getName()));;
Stream.of(data2).forEach(System.out::println);
System.out.println("-----------------");
Stu zhaoliu = new Stu(1004, "zhaoliu", 88.8f);
Stu liusong = new Stu(1002, "liusong", 78.8f);
Stu[] data3 = {zhangsan,lisi,zhaoliu,liusong,wanger,mazi,qianwu};
Arrays.sort(data3,(stu1,stu2)->{
if(stu1.getId() != stu2.getId()){
return stu1.getName().length()-stu2.getName().length();
}else {
return stu1.getId()-stu2.getId();
}
});
Stream.of(data3).forEach(System.out::println);
}