Java中使用Lambda表达式对集合排序
短信预约 -IT技能 免费直播动态提醒
文章目录
一.利用lambda对list集合排序
先定义一个集合
List<Integer> list = new ArrayList<>();list.add(1);list.add(5);list.add(4);list.add(3);list.add(7);
1.升序排序
list.sort((a,b)->a.compareTo(b));
或
list.sort(Comparator.comparing(a->a));
或
list.sort((a,b)->a-b);
或
// 2、匿名内部类list.sort(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return o1-o2;}});
2.降序排序
list.sort((a,b)->b-a);
匿名内部类方法
list.sort(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2-o1; } });
对对象集合操作,其实与基本类型集合操作类似
List<User> list1 = new ArrayList<User>();User user = new User("张三", "15", "男");User user1 = new User("李四", "10", "男");list1.add(user);list1.add(user1);//1、年龄升序list1.sort((a,b) -> a.getAge().compareTo(b.getAge()));//2、姓名降序排列list1.sort(Comparator.comparing(User::getName).reversed());//等价于 2list1.sort(Comparator.comparing(a->((User)a).getAge()).reversed());//3、先按性别排,如果年龄相同,再按年龄排序list1.sort(Comparator.comparing(User::getSex).reversed().thenComparing(User::getAge));
对 JSONArray 排序
定义一个json数组 resultArray
JSONArray resultArray = new JSONArray();JSONObject result = new JSONObject();result.put("name","张三");result.put("age","15");result.put("data","201812130451");resultArray.add(result);//根据姓名的倒序排序resultArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("name")).reversed());//根据时间倒序排序resultArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getData("data")).reversed());//根据年龄升序排序resultArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("age")));
注意:reversed()函数的意思是将数组颠倒。其用法常见于字符串处理中,将字符串颠倒
如:
String str = "abcd";StringBuffer sb = new StringBuffer(str);sb.reverse();System.out.println(str);System.out.println(sb.toString());---------------------------------------输出abcddcba
二.java8-Lambda中比较器Comparator的使用
典型的比较器示例
Comparator<Developer> byName = new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getName().compareTo(o2.getName()); }};
等价的Lambda的方式
Comparator<Developer> byName = (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());
不使用Lambda的排序
假如我们要通过Developer 对象的年龄进行排序,通常情况下我们使用Collections.sort,new个匿名Comparator 类,类似下面这种:
import java.math.BigDecimal;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class TestSorting { public static void main(String[] args) { List<Developer> listDevs = getDevelopers(); System.out.println("Before Sort"); for (Developer developer : listDevs) { System.out.println(developer); } //sort by age Collections.sort(listDevs, new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getAge() - o2.getAge(); } }); System.out.println("After Sort"); for (Developer developer : listDevs) { System.out.println(developer); } } private static List<Developer> getDevelopers() { List<Developer> result = new ArrayList<Developer>(); result.add(new Developer("ricky", new BigDecimal("70000"), 33)); result.add(new Developer("alvin", new BigDecimal("80000"), 20)); result.add(new Developer("jason", new BigDecimal("100000"), 10)); result.add(new Developer("iris", new BigDecimal("170000"), 55)); return result; }}-----------------------------------------------------------------------------------------------------输出结果:Before SortDeveloper [name=ricky, salary=70000, age=33]Developer [name=alvin, salary=80000, age=20]Developer [name=jason, salary=100000, age=10]Developer [name=iris, salary=170000, age=55]After SortDeveloper [name=jason, salary=100000, age=10]Developer [name=alvin, salary=80000, age=20]Developer [name=ricky, salary=70000, age=33]Developer [name=iris, salary=170000, age=55]
当比较规则发生变化时,你需要再次new个匿名Comparator 类:
//sort by age Collections.sort(listDevs, new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getAge() - o2.getAge(); } }); //sort by name Collections.sort(listDevs, new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getName().compareTo(o2.getName()); } }); //sort by salary Collections.sort(listDevs, new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getSalary().compareTo(o2.getSalary()); } });
这样也可以,不过你会不会觉得这样有点怪,因为其实不同的只有一行代码而已,但是却需要重复写很多代码?
通过Lambda进行排序
在java8中,List接口直接提供了排序方法, 所以你不需要使用Collections.sort
//List.sort() since Java 8 listDevs.sort(new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o2.getAge() - o1.getAge(); } });
Lambda 示例
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;public class TestSorting { public static void main(String[] args) { List<Developer> listDevs = getDevelopers(); System.out.println("Before Sort"); for (Developer developer : listDevs) { System.out.println(developer); } System.out.println("After Sort"); //lambda here! listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge()); //java 8 only, lambda also, to print the List listDevs.forEach((developer)->System.out.println(developer)); } private static List<Developer> getDevelopers() { List<Developer> result = new ArrayList<Developer>(); result.add(new Developer("ricky", new BigDecimal("70000"), 33)); result.add(new Developer("alvin", new BigDecimal("80000"), 20)); result.add(new Developer("jason", new BigDecimal("100000"), 10)); result.add(new Developer("iris", new BigDecimal("170000"), 55)); return result; }}------------------------------------------------------------------------输出结果:Before SortDeveloper [name=ricky, salary=70000, age=33]Developer [name=alvin, salary=80000, age=20]Developer [name=jason, salary=100000, age=10]Developer [name=iris, salary=170000, age=55]After SortDeveloper [name=jason, salary=100000, age=10]Developer [name=alvin, salary=80000, age=20]Developer [name=ricky, salary=70000, age=33]Developer [name=iris, salary=170000, age=55]
更多的Lambda例子
根据年龄
//sort by age Collections.sort(listDevs, new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getAge() - o2.getAge(); } }); //lambda listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge()); //lambda, valid, parameter type is optional listDevs.sort((o1, o2)->o1.getAge()-o2.getAge());
根据名字
//sort by name Collections.sort(listDevs, new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getName().compareTo(o2.getName()); } }); //lambda listDevs.sort((Developer o1, Developer o2)->o1.getName().compareTo(o2.getName())); //lambda listDevs.sort((o1, o2)->o1.getName().compareTo(o2.getName()));
根据薪水
//sort by salary Collections.sort(listDevs, new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getSalary().compareTo(o2.getSalary()); } }); //lambda listDevs.sort((Developer o1, Developer o2)->o1.getSalary().compareTo(o2.getSalary())); //lambda listDevs.sort((o1, o2)->o1.getSalary().compareTo(o2.getSalary()))
倒序
正常排序
Comparator<Developer> salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary());listDevs.sort(salaryComparator);
倒序
Comparator<Developer> salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary());listDevs.sort(salaryComparator.reversed());
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341