首页 / JAVA / Java8比较器(Lamdba)
Java8比较器(Lamdba)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java8比较器(Lamdba),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2584字,纯文字阅读大概需要4分钟。
内容图文
1、首先构造一个实体以便示例使用
public class Developer { private String name; private BigDecimal salary; private int age; public Developer(String name, BigDecimal salary, int age) { this.name = name; this.salary = salary; this.age = age; } public String getName() { return name; } publicvoid setName(String name) { this.name = name; } public BigDecimal getSalary() { return salary; } publicvoid setSalary(BigDecimal salary) { this.salary = salary; } publicint getAge() { return age; } publicvoid setAge(int age) { this.age = age; } @Override public String toString() { return "Developer{" + "name=‘" + name + ‘\‘‘ + ", salary=" + salary + ", age=" + age + ‘}‘; } }
2、在Java8之前排序的方式
public class TestSorting { public static void main(String[] args) { List<Developer> listDevs = getDevelopers(); Collections.sort(listDevs, new Comparator<Developer>() { @Override publicint compare(Developer o1, Developer o2) { return o1.getAge() - o2.getAge(); } }); for (Developer developer : listDevs) { System.out.println(developer); } } privatestatic List<Developer> getDevelopers() { List<Developer> result = new ArrayList<Developer>(); result.add(new Developer("mkyong", 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("10000"), 23)); return result; } }
3、在Java8使用Lamdba排序
public class TestSortingLamdba {
public static void main(String[] args) {
List<Developer> listDevs = getDevelopers();
listDevs.sort((Developer o1, Developer o2) -> o1.getAge() - o2.getAge());
listDevs.forEach(System.out::println);
System.out.println("----------------");
listDevs.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
listDevs.forEach(System.out::println);
System.out.println("----------------");
listDevs.sort(Comparator.comparing(Developer::getSalary));
listDevs.forEach(System.out::println);
System.out.println("----------------");
listDevs.sort(Comparator.comparing(Developer::getSalary).reversed());
listDevs.forEach(System.out::println);
}
private static List<Developer> getDevelopers() {
List<Developer> result = new ArrayList<Developer>();
result.add(new Developer("mkyong", 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("10000"), 23));
return result;
}
}
原文:https://www.cnblogs.com/fengkunangel/p/10421411.html
内容总结
以上是互联网集市为您收集整理的Java8比较器(Lamdba)全部内容,希望文章能够帮你解决Java8比较器(Lamdba)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。