设为首页 加入收藏

TOP

Lambda表达式 List排序进阶(一)
2018-11-20 22:09:37 】 浏览:405
Tags:Lambda 表达式 List 排序 进阶

初始代码:


一个Apple类


public class Apple{
    String color;
    Integer size;
    Float weight;
   
    public Apple() {
    }


    public Apple(String color, Integer size, Float weight) {
        this.color = color;
        this.size = size;
        this.weight = weight;
    }


    public String getColor() {
        return color;
    }


    public void setColor(String color) {
        this.color = color;
    }


    public Integer getSize() {
        return size;
    }


    public void setSize(Integer size) {
        this.size = size;
    }


    public Float getWeight() {
        return weight;
    }


    public void setWeight(Float weight) {
        this.weight = weight;
    }


    @Override
    public String toString() {
        return "Apple{" +
                "weight=" + weight +
                ", size=" + size +
                ", color=" + color +
                '}';
    }
}


主函数 一个赋值一个打印


    public static void main(String[] args) {
        List<Apple> appleList = new ArrayList<>();
        appleList.add(new Apple("red",111,333F));
        appleList.add(new Apple("yellow",333,222F));
        appleList.add(new Apple("blue",222,888F));
        appleList.add(new Apple("black",555,777F));
        appleList.add(new Apple("pink",444,111F));
        appleList.add(new Apple("green",666,444F));
    }


    private static <T> void forEach(List<T> list){
        for(Object vo : list){
            System.out.println(vo.toString());
        }
    }


第一级:传递代码


Apple类实现Comparator 复写compare


public class Apple implements Comparator<Apple> {
    String color;
    Integer size;
    Float weight;


    @Override
    public int compare(Apple o1, Apple o2) {
        return o1.getSize().compareTo(o2.getSize());
    }
   
    ……
}


        appleList.sort(new Apple());
        forEach(appleList);


打印结果:



第二级:匿名类


Apple类还原 不用实现Comparator


        appleList.sort(new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                return o1.getSize().compareTo(o2.getSize());
            }
        });
        forEach(appleList);


打印结果一样


第三级:使用Lambda表达式


一样的传递代码 轻量的写法


        a

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇HTTPS心得笔记之OpenSSL生成root .. 下一篇Python 机器学习的必备技巧

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目