java构造比较器_Java8比较器(Lamdba)

1、首先构造一个实体以便示例使用

public classDeveloper {privateString name;privateBigDecimal salary;private intage;public Developer(String name, BigDecimal salary, intage) {this.name =name;this.salary =salary;this.age =age;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}publicBigDecimal getSalary() {returnsalary;

}public voidsetSalary(BigDecimal salary) {this.salary =salary;

}public intgetAge() {returnage;

}public void setAge(intage) {this.age =age;

}

@OverridepublicString toString() {return "Developer{" +

"name='" + name + '\'' +

", salary=" + salary +

", age=" + age +

'}';

}

}

2、在Java8之前排序的方式

public classTestSorting {public static voidmain(String[] args) {

List listDevs =getDevelopers();

Collections.sort(listDevs,new Comparator() {

@Overridepublic intcompare(Developer o1, Developer o2) {return o1.getAge() -o2.getAge();

}

});for(Developer developer : listDevs) {

System.out.println(developer);

}

}private static ListgetDevelopers() {

List result = new ArrayList();

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));returnresult;

}

}

3、在Java8使用Lamdba排序

public class TestSortingLamdba {

public static void main(String[] args) {

List 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 getDevelopers() {

List result = new ArrayList();

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值