java集合Collections.sort()的方法应用
程序员文章站
2022-05-12 17:49:02
...
简单介绍集合工具类sort()的方法应用,简单类型排序和根据对象字段来排序.代码如下:
public class SomeTest {
public static void main(String[] args) {
SomeTest st = new SomeTest();
List<String> list = new ArrayList<>();
list.add("bu");
list.add("cu");
list.add("ca");
list.add("a");
Collections.sort(list);//简单排序
System.out.println(list);
//对象排序
List<employee> strList = new ArrayList<>();
employee e1 = st.new employee("bily", 10, 18000);
employee e2 = st.new employee("fulosa", 10, 16000);
employee e3 = st.new employee("aiwen", 10, 17000);
employee e4 = st.new employee("cicy", 10, 13000);
strList.add(e1);
strList.add(e2);
strList.add(e3);
strList.add(e4);
/**有几种自定义API,根据类型来选择*/
strList.sort(Comparator.comparingDouble(employee::getSalary));//排序,根据工资
System.out.println(strList.toString());
strList.sort(Comparator.comparingDouble(employee::getSalary).reversed());//自定义排序逆序
System.out.println(strList.toString());
strList.sort(Comparator.comparing(employee::getName));//根据名字排序,调用String类型的比较方法
System.out.println(strList.toString());
}
class employee{
private String name;
private int age;
private double salary;
public employee(String name,int age, double salary){
this.name=name;
this.age=age;
this.salary=salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "employee [name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
}
}
结果输出:
[a, bu, ca, cu]
[employee [name=cicy, age=10, salary=13000.0], employee [name=fulosa, age=10, salary=16000.0], employee [name=aiwen, age=10, salary=17000.0], employee [name=bily, age=10, salary=18000.0]]
[employee [name=bily, age=10, salary=18000.0], employee [name=aiwen, age=10, salary=17000.0], employee [name=fulosa, age=10, salary=16000.0], employee [name=cicy, age=10, salary=13000.0]]
[employee [name=aiwen, age=10, salary=17000.0], employee [name=bily, age=10, salary=18000.0], employee [name=cicy, age=10, salary=13000.0], employee [name=fulosa, age=10, salary=16000.0]]
推荐阅读
-
PHP静态调用非静态方法的应用分析_php实例
-
jQuery中的$.ajax()方法应用_jquery
-
java并发请求下数据插入重复问题的解决方法
-
应用程序发生异常 unknown software exception的解决方法
-
java WebSocket客户端断线重连的实现方法
-
Session[""]如何判断存入空集合的值为空? 企业应用
-
Windows下支持自动更新的Electron应用脚手架的方法
-
Spring获取Web应用根目录的方法 WebSpringlog4jIBMServlet
-
python利用递归方法实现求集合的幂集
-
C# ComboBox控件“设置 DataSource 属性后无法修改项集合”的完美解决方法