Java8 用Lambda表达式给List集合排序的实现
2019-10-31 07:05
3823 查看
Lambda用到了JDK8自带的一个函数式接口Comparator<T>。
准备一个Apple类
public class Apple { private int weight; private String color; public Apple(){} public Apple(int weight) { this.weight = weight; } public Apple(int weight, String color) { this.weight = weight; this.color = color; } setters();getters();toString(); }
步骤一:
public class AppleComparator implements Comparator<Apple> { @Override public int compare(Apple o1, Apple o2) { return o1.getWeight() - o2.getWeight(); } }
步骤二:准备一个List集合
ArrayList<Apple> inventory = Lists.newArrayList( new Apple(10, "red"), new Apple(5, "red"), new Apple(1, "green"), new Apple(15, "green"), new Apple(2, "red"));
步骤三:顺序排序,三种方式
/** * 顺序排序 */ // 1、传递代码,函数式编程 inventory.sort(new AppleComparator()); System.out.println(inventory); // 2、匿名内部类 inventory.sort(new Comparator<Apple>() { @Override public int compare(Apple o1, Apple o2) { return o1.getWeight() - o2.getWeight(); } }); // 3、使用Lambda表达式 inventory.sort((a, b) -> a.getWeight() - b.getWeight()); // 4、使用Comparator的comparing Comparator<Apple> comparing = comparing((Apple a) -> a.getWeight()); inventory.sort(comparing((Apple a) -> a.getWeight())); //或者等价于 inventory.sort(comparing(Apple::getWeight));
步骤四:逆序排序
/** * 逆序排序 */ // 1、 根据重量逆序排序 inventory.sort(comparing(Apple::getWeight).reversed());
步骤五:如果两个苹果一样重,就得再找一个条件来进行排序
// 2、如果两个苹果的重量一样重,怎么办?那就再找一个条件进行排序呗 inventory.sort(comparing(Apple::getWeight).reversed().thenComparing(Apple::getColor));
https://gitee.com/play-happy/base-project
参考:
【1】《Java8实战》
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- Java实现List集合排序
- java 策略模式,list集合,实现id 姓名年龄正序倒序排序(如果年龄或者姓名重复,按id正序排序)
- Java实现根据List中对象的相应属性进行排序
- 120941138:java list sort()排序各种方式,实现接口
- Java基础知识强化之集合框架笔记29:使用LinkedList实现栈数据结构的集合代码(面试题)
- 2.当形参,返回值类型是JavaBean式的复合类,List集合,数组等时:服务端实现类
- Java集合源码学习(8)_List接口的实现_CopyOnWriteArrayList
- Java中对List集合的排序
- java中List集合的遍历和两种实现类的比较分析
- (好使)用Java集合中的Collections.sort方法对list排序的两种方法
- Java:集合,对列表(List)中的自定义对象按属性(字段)排序(正序、倒序)的方法
- Java中List集合的遍历和两种实现类的比较分析
- Java集合排序及java集合类详解--(Collection, List, Set, Map)
- java实现List中对象排序的方法
- java 之Sting类型的List集合的汉字排序和String类型数组的汉字排序及List<Bean>排序
- Java集合之ArrayList和LinkedList的实现原理以及Iterator详解
- java Collections.sort()实现List排序的默认方法和自定义方法
- Java集合对象的排序使用Collection.sort方法,先实现Comparable接口
- java中对List中对象排序实现
- list集合绑定在datagridview上时如何实现排序