从京东看 lambda 的威力

在这里插入图片描述

在京东购物的对这个再熟悉不过了。那么,这个 lambda 有什么关系呢? 让我为你一一道来。

首先定义一个产品对象

package com.example.test;

import java.util.Objects;

public class Product {

    private final String id;

    private int salesVolume;

    private int comments;

    private long createTime;

    private int price;

    private boolean isJDLogistic;

    private boolean isCashOnDelivery;

    private boolean isInStock;

    private boolean isGlobalBuy;

    private boolean isGlobalDistribution;

    private Product(Builder builder) {
        this.id = builder.id;
        this.salesVolume = builder.salesVolume;
        this.comments = builder.comments;
        this.createTime = builder.createTime;
        this.price = builder.price;
        this.isJDLogistic = builder.isJDLogistic;
        this.isCashOnDelivery = builder.isCashOnDelivery;
        this.isInStock = builder.isInStock;
        this.isGlobalBuy = builder.isGlobalBuy;
        this.isGlobalDistribution = builder.isGlobalDistribution;
    }

    public String getId() {
        return id;
    }

    public int getSalesVolume() {
        return salesVolume;
    }

    public int getComments() {
        return comments;
    }

    public long getCreateTime() {
        return createTime;
    }

    public int getPrice() {
        return price;
    }

    public boolean isJDLogistic() {
        return isJDLogistic;
    }

    public boolean isCashOnDelivery() {
        return isCashOnDelivery;
    }

    public boolean isInStock() {
        return isInStock;
    }

    public boolean isGlobalBuy() {
        return isGlobalBuy;
    }

    public boolean isGlobalDistribution() {
        return isGlobalDistribution;
    }

    static class Builder {

        final private String id;

        int salesVolume;

        int comments;

        long createTime;

        int price;

        boolean isJDLogistic;

        boolean isCashOnDelivery;

        boolean isInStock;

        boolean isGlobalBuy;

        boolean isGlobalDistribution;

        public Builder(String id) {
            this.id = id;
        }

        public Builder salesVolume(int salesVolume) {
            this.salesVolume = salesVolume;
            return this;
        }

        public Builder comments(int comments) {
            this.comments = comments;
            return this;
        }

        public Builder createTime(long createTime) {
            this.createTime = createTime;
            return this;
        }

        public Builder price(int price) {
            this.price = price;
            return this;
        }

        public Builder isJDLogistic(boolean isJDLogistic) {
            this.isJDLogistic = isJDLogistic;
            return this;
        }

        public Builder isCashOnDelivery(boolean isCashOnDelivery) {
            this.isCashOnDelivery = isCashOnDelivery;
            return this;
        }

        public Builder isInStock(boolean isInStock) {
            this.isInStock = isInStock;
            return this;
        }

        public Builder isGlobalBuy(boolean isGlobalBuy) {
            this.isGlobalBuy = isGlobalBuy;
            return this;
        }

        public Builder isGlobalDistribution(boolean isGlobalDistribution) {
            this.isGlobalDistribution = isGlobalDistribution;
            return this;
        }

        public Product build() {
            return new Product(this);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
        {
            return true;
        }
        Product o = (Product)obj;
        return Objects.equals(id, o.id);
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }
}

由于 Product 有多个属性,因此,采用 Builder 模式。

第一版

package com.example.test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class JDFilterByClass {

    public static void main(String[] args) {

        Product p1 = new Product.Builder("1").salesVolume(1).comments(1).createTime(1)
                .price(1).isJDLogistic(true).isCashOnDelivery(true).isInStock(true)
                .isGlobalDistribution(true).isGlobalBuy(true).build();
        Product p2 = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        Product productSpec = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        List<Product> products = new ArrayList<>();
        products.add(p1);
        products.add(p2);
        new JDFilterByClass().fileterByComparatorAnonymousClass(products, productSpec);
    }

    List<Product> fileterByComparatorAnonymousClass(List<Product> products, Product productSpec) {
        List<Product> newProducts = fileterByIsCashOnDelivery(products, productSpec.isCashOnDelivery());
        newProducts = fileterByIsGlobalBuy(newProducts, productSpec.isGlobalBuy());
        newProducts = fileterByIsInstock(newProducts, productSpec.isInStock());
        newProducts = fileterByIsGlobalDistribution(newProducts, productSpec.isGlobalDistribution());
        newProducts = fileterByIsJDLogistic(newProducts, productSpec.isJDLogistic());
        newProducts.sort(new ComparatorByComments());
        newProducts.sort(new ComparatorBySaleVolume());
        newProducts.sort(new ComparatorByPrice());
        newProducts.sort(new ComparatorByCreateTime());
        return newProducts;

    }

    List<Product> fileterByIsGlobalBuy(List<Product> products, boolean isGlobalBuy) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product p : products) {
            if (fileterByIsGlobalBuy(p, isGlobalBuy)) {
                filteredProducts.add(p);
            }
        }
        return filteredProducts;
    }

    boolean fileterByIsGlobalBuy(Product product, boolean isGlobalBuy) {
        if (product.isGlobalBuy() == isGlobalBuy) {
            return true;
        } else {
            return false;
        }
    }

    List<Product> fileterByIsGlobalDistribution(List<Product> products, boolean isGlobalDistribution) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product p : products) {
            if (fileterByIsGlobalDistribution(p, isGlobalDistribution)) {
                filteredProducts.add(p);
            }
        }
        return filteredProducts;
    }

    boolean fileterByIsGlobalDistribution(Product product, boolean isGlobalDistribution) {
        if (product.isGlobalDistribution() == isGlobalDistribution) {
            return true;
        } else {
            return false;
        }
    }

    List<Product> fileterByIsInstock(List<Product> products, boolean isStock) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product p : products) {
            if (fileterByIsInStock(p, isStock)) {
                filteredProducts.add(p);
            }
        }
        return filteredProducts;
    }

    boolean fileterByIsInStock(Product product, boolean isInStock) {
        if (product.isInStock() == isInStock) {
            return true;
        } else {
            return false;
        }
    }

    List<Product> fileterByIsJDLogistic(List<Product> products, boolean isJDLogistic) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product p : products) {
            if (fileterByIsJDLogistic(p, isJDLogistic)) {
                filteredProducts.add(p);
            }
        }
        return filteredProducts;
    }

    boolean fileterByIsJDLogistic(Product product, boolean isJDLogistic) {
        if (product.isJDLogistic() == isJDLogistic) {
            return true;
        } else {
            return false;
        }
    }

    List<Product> fileterByIsCashOnDelivery(List<Product> products, boolean isCashOnDelivery) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product p : products) {
            if (fileterByIsCashOnDelivery(p, isCashOnDelivery)) {
                filteredProducts.add(p);
            }
        }
        return filteredProducts;
    }

    boolean fileterByIsCashOnDelivery(Product product, boolean isCashOnDelivery) {
        if (product.isCashOnDelivery() == isCashOnDelivery) {
            return true;
        } else {
            return false;
        }
    }


    class ComparatorByPrice implements Comparator<Product> {
        @Override
        public int compare(Product o1, Product o2) {
            if (o1.getPrice() > o2.getPrice()) {
                return 1;
            } else if (o1.getPrice() == o2.getPrice()) {
                return 0;
            } else {
                return -1;
            }
        }
    }

    class ComparatorByComments implements Comparator<Product> {
        @Override
        public int compare(Product o1, Product o2) {
            if (o1.getComments() > o2.getComments()) {
                return 1;
            } else if (o1.getComments() == o2.getComments()) {
                return 0;
            } else {
                return -1;
            }
        }
    }

    class ComparatorBySaleVolume implements Comparator<Product> {
        @Override
        public int compare(Product o1, Product o2) {
            if (o1.getSalesVolume() > o2.getSalesVolume()) {
                return 1;
            } else if (o1.getSalesVolume() == o2.getSalesVolume()) {
                return 0;
            } else {
                return -1;
            }
        }
    }

    class ComparatorByCreateTime implements Comparator<Product> {
        @Override
        public int compare(Product o1, Product o2) {
            if (o1.getCreateTime() > o2.getCreateTime()) {
                return 1;
            } else if (o1.getCreateTime() == o2.getCreateTime()) {
                return 0;
            } else {
                return -1;
            }
        }
    }
}

对于比较,我们只需要实现 Comparator 接口即可。对于过滤,由于条件不固定,无法统一处理。这里,对于不同的类型的条件,通过一个函数来实现。

优点:简单,直观,是初入职场的程序的典型实现

缺点:违背开闭原则,新增过滤条件,就要新增函数来处理。而且唯一的就是过滤条件,有大量的重复代码。而实际业务系统的条件不止 3-4 个,复杂的业务几十个也是很正常的。遇到这种情况,这个类会混杂不堪。

第二版

IFilterProduct.java

package com.example.test;

public interface IFilterProduct {
    boolean isMatch(Product p, Product productSpec);
}

JDFilterByInterfaceClass.java

package com.example.test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class JDFilterByInterfaceClass {

    public static void main(String[] args) {
        Product p1 = new Product.Builder("1").salesVolume(1).comments(1).createTime(1)
                .price(1).isJDLogistic(true).isCashOnDelivery(true).isInStock(true)
                .isGlobalDistribution(true).isGlobalBuy(true).build();
        Product p2 = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        Product productSpec = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        List<Product> products = new ArrayList<>();
        products.add(p1);
        products.add(p2);
        new JDFilterByAbstractClass().fileterByComparatorAbstractClass(products, productSpec);
    }

    List<Product> fileterByComparatorAbstractClass(List<Product> products, Product productSpec) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product p : products) {
            IFilterProduct filterByIsCacheOnDelivery = new FileterByIsCashOnDelivery();
            IFilterProduct fileterByIsGlobalBuy = new FileterByIsGlobalBuy();
            IFilterProduct fileterByIsGlobalDistribution = new FileterByIsGlobalDistribution();
            IFilterProduct fileterByIsInStock = new FileterByIsInStock();
            IFilterProduct fileterByIsJDLogistic = new FileterByIsJDLogistic();
            if (filterByIsCacheOnDelivery.isMatch(p, productSpec)
                    && fileterByIsGlobalBuy.isMatch(p, productSpec)
                    && fileterByIsGlobalDistribution.isMatch(p, productSpec)
                    && fileterByIsInStock.isMatch(p, productSpec)
                    && fileterByIsJDLogistic.isMatch(p, productSpec)) {
                filteredProducts.add(p);
            }
        }
        filteredProducts.sort(new ComparatorByComments());
        filteredProducts.sort(new ComparatorBySaleVolume());
        filteredProducts.sort(new ComparatorByPrice());
        filteredProducts.sort(new ComparatorByCreateTime());
        return filteredProducts;
    }
}

FileterByIsGlobalDistribution.java

    class FileterByIsGlobalDistribution implements IFilterProduct {
        @Override
        public boolean isMatch(Product product, Product productSpec) {
            if (product.isGlobalDistribution() == productSpec.isGlobalDistribution()) {
                return true;
            } else {
                return false;
            }
        }
    }

FileterByIsInStock.java

    class FileterByIsInStock implements IFilterProduct {
        @Override
        public boolean isMatch(Product product, Product productSpec) {
            if (product.isInStock() == productSpec.isInStock()) {
                return true;
            } else {
                return false;
            }
        }
    }

FileterByIsJDLogistic.java

    class FileterByIsJDLogistic implements IFilterProduct {
        @Override
        public boolean isMatch(Product product, Product productSpec) {
            if (product.isJDLogistic() == productSpec.isJDLogistic()) {
                return true;
            } else {
                return false;
            }
        }
    }

FileterByIsCashOnDelivery.java

    class FileterByIsCashOnDelivery implements IFilterProduct {
        @Override
        public boolean isMatch(Product product, Product productSpec) {
            if (product.isCashOnDelivery() == productSpec.isCashOnDelivery()) {
                return true;
            } else {
                return false;
            }
        }

    }

FileterByIsGlobalBuy.java

   class FileterByIsGlobalBuy implements IFilterProduct {
        @Override
        public boolean isMatch(Product product, Product productSpec) {
            if (product.isGlobalBuy() == productSpec.isGlobalBuy()) {
                return true;
            } else {
                return false;
            }
        }
    }

这版较上一版本,抽象出统一的过滤条件,更加解耦,对于排序和过滤,新的排序和过滤通过实现接口即可扩展。遵守了开闭原则。

IFilterProduct 接口将所有的过滤抽象,其中 isMatch 方法,返回 boolean,称为谓词。IFilterProduct 及其实现,与策略模式异曲同工。

这个解决办法,需要一定的经验的程序员,并且说明初具抽象能力。

第三版

IFilter.java

package com.example.test;

public interface IFilter<T, V> {
    boolean isMatch(T t, V v);
}

JDFilterByInterfaceClass.java

package com.example.test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class JDFilterByAbstractClass {

    public static void main(String[] args) {
        Product p1 = new Product.Builder("1").salesVolume(1).comments(1).createTime(1)
                .price(1).isJDLogistic(true).isCashOnDelivery(true).isInStock(true)
                .isGlobalDistribution(true).isGlobalBuy(true).build();
        Product p2 = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        Product productSpec = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        List<Product> products = new ArrayList<>();
        products.add(p1);
        products.add(p2);
        new JDFilterByAbstractClass().fileterByComparatorAbstractClass(products, productSpec);
    }

    List<Product> fileterByComparator(List<Product> products, Product productSpec) {
        List<Product> filteredProducts = new ArrayList<>();
        filteredProducts = filter(products, productSpec, new FileterByIsCashOnDelivery());
        filteredProducts = filter(filteredProducts, productSpec, new FileterByIsGlobalBuy());
        filteredProducts = filter(filteredProducts, productSpec, new FileterByIsGlobalDistribution());
        filteredProducts = filter(filteredProducts, productSpec, new FileterByIsInStock());
        filteredProducts = filter(filteredProducts, productSpec, new FileterByIsJDLogistic());
        filteredProducts.sort(new ComparatorByComments());
        filteredProducts.sort(new ComparatorBySaleVolume());
        filteredProducts.sort(new ComparatorByPrice());
        filteredProducts.sort(new ComparatorByCreateTime());
        return filteredProducts;
    }


    List<Product> filter(List<Product> products, Product productSpec, IFilter<Product,Product> filter) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product p : products) {
            if (filter.isMatch(p, productSpec))
            {
                filteredProducts.add((p));
            }
        }
        return filteredProducts;
    }
}

FileterByIsGlobalBuy.java

   class FileterByIsGlobalBuy implements IFilter<Product, Product> {
        @Override
        public boolean isMatch(Product product, Product productSpec) {
            if (product.isGlobalBuy() == productSpec.isGlobalBuy()) {
                return true;
            } else {
                return false;
            }
        }
    }

FileterByIsGlobalDistribution.java

    class FileterByIsGlobalDistribution implements IFilter<Product, Product> {
        @Override
        public boolean isMatch(Product product, Product productSpec) {
            if (product.isGlobalDistribution() == productSpec.isGlobalDistribution()) {
                return true;
            } else {
                return false;
            }
        }
    }

FileterByIsInStock.java

    class FileterByIsInStock implements IFilter<Product, Product> {
        @Override
        public boolean isMatch(Product product, Product productSpec) {
            if (product.isInStock() == productSpec.isInStock()) {
                return true;
            } else {
                return false;
            }
        }
    }

FileterByIsJDLogistic.java

class FileterByIsJDLogistic implements IFilter<Product, Product> {
    @Override
    public boolean isMatch(Product product, Product productSpec) {
        if (product.isJDLogistic() == productSpec.isJDLogistic()) {
            return true;
        } else {
            return false;
        }
    }
}

FileterByIsCashOnDelivery.java

    class FileterByIsCashOnDelivery implements IFilter<Product, Product> {
        @Override
        public boolean isMatch(Product product, Product productSpec) {
            if (product.isCashOnDelivery() == productSpec.isCashOnDelivery()) {
                return true;
            } else {
                return false;
            }
        }

    }

ComparatorByPrice.java

    class ComparatorByPrice implements Comparator<Product> {
        @Override
        public int compare(Product o1, Product o2) {
            if (o1.getPrice() > o2.getPrice()) {
                return 1;
            } else if (o1.getPrice() == o2.getPrice()) {
                return 0;
            } else {
                return -1;
            }
        }
    }

ComparatorByComments.java

    class ComparatorByComments implements Comparator<Product> {
        @Override
        public int compare(Product o1, Product o2) {
            if (o1.getComments() > o2.getComments()) {
                return 1;
            } else if (o1.getComments() == o2.getComments()) {
                return 0;
            } else {
                return -1;
            }
        }
    }

ComparatorBySaleVolume.java

class ComparatorBySaleVolume implements Comparator<Product> {
        @Override
        public int compare(Product o1, Product o2) {
            if (o1.getSalesVolume() > o2.getSalesVolume()) {
                return 1;
            } else if (o1.getSalesVolume() == o2.getSalesVolume()) {
                return 0;
            } else {
                return -1;
            }
        }
}

ComparatorByCreateTime.java

class ComparatorByCreateTime implements Comparator<Product> {
        @Override
        public int compare(Product o1, Product o2) {
            if (o1.getCreateTime() > o2.getCreateTime()) {
                return 1;
            } else if (o1.getCreateTime() == o2.getCreateTime()) {
                return 0;
            } else {
                return -1;
            }
        }
}

这版较上一版本,对 Filter 的抽象更加通用。如果 Product 的过滤条件可以不是 Product,也可以是其他对象。

此外,filter 函数采用行为化参数,显示出作者较为成熟的抽象能力。

版本四

package com.example.test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class JDFilterByAnonymousClass {

    public static void main(String[] args) {
        Product p1 = new Product.Builder("1").salesVolume(1).comments(1).createTime(1)
                .price(1).isJDLogistic(true).isCashOnDelivery(true).isInStock(true)
                .isGlobalDistribution(true).isGlobalBuy(true).build();
        Product p2 = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        Product productSpec = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        List<Product> products = new ArrayList<>();
        products.add(p1);
        products.add(p2);
        new JDFilterByAnonymousClass().fileterByComparatorAnonymousClass(products, productSpec);
    }


    List<Product> fileterByComparatorAnonymousClass(List<Product> products, Product productSpec) {

        IFilter<Product,Product> fileterByIsGlobalBuy  = new IFilter<Product, Product>() {
            @Override
            public boolean isMatch(Product product, Product productSpec) {
                if (product.isGlobalBuy() == productSpec.isGlobalBuy()) {
                    return true;
                } else {
                    return false;
                }
            }
        };

        IFilter<Product, Product> fileterByIsGlobalDistribution = new IFilter<Product, Product>() {
            @Override
            public boolean isMatch(Product product, Product productSpec) {
                if (product.isGlobalDistribution() == productSpec.isGlobalDistribution()) {
                    return true;
                } else {
                    return false;
                }
            }
        };

        IFilter<Product, Product> fileterByIsInStock = new IFilter<Product, Product>() {
            @Override
            public boolean isMatch(Product product, Product productSpec) {
                if (product.isInStock() == productSpec.isInStock()) {
                    return true;
                } else {
                    return false;
                }
            }
        };

        IFilter<Product, Product> fileterByIsJDLogistic = new IFilter<Product, Product>() {
            @Override
            public boolean isMatch(Product product, Product productSpec) {
                if (product.isJDLogistic() == productSpec.isJDLogistic()) {
                    return true;
                } else {
                    return false;
                }
            }
        };

        IFilter<Product, Product> filterByIsCashOnDelivery = new IFilter<Product, Product>() {
            @Override
            public boolean isMatch(Product product, Product productSpec) {
                if (product.isCashOnDelivery() == productSpec.isCashOnDelivery()) {
                    return true;
                } else {
                    return false;
                }
            }
        };

        Comparator<Product> comparatorBySaleVolume = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                if (o1.getSalesVolume() > o2.getSalesVolume()) {
                    return 1;
                } else if (o1.getSalesVolume() == o2.getSalesVolume()) {
                    return 0;
                } else {
                    return -1;
                }
            }
        };

        Comparator<Product> comparatorByComments = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                if (o1.getComments() > o2.getComments()) {
                    return 1;
                } else if (o1.getComments() == o2.getComments()) {
                    return 0;
                } else {
                    return -1;
                }
            }
        };

        Comparator<Product> comparatorByCreateTime = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                if (o1.getCreateTime() > o2.getCreateTime()) {
                    return 1;
                } else if (o1.getCreateTime() == o2.getCreateTime()) {
                    return 0;
                } else {
                    return -1;
                }
            }
        };

        Comparator<Product> comparatorByPrice = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                if (o1.getPrice() > o2.getPrice()) {
                    return 1;
                } else if (o1.getPrice() == o2.getPrice()) {
                    return 0;
                } else {
                    return -1;
                }
            }
        };

        
        List<Product> filteredProducts = new ArrayList<>();
        filteredProducts = filter(filteredProducts, productSpec, filterByIsCashOnDelivery);
        filteredProducts = filter(filteredProducts, productSpec, fileterByIsJDLogistic );
        filteredProducts = filter(filteredProducts, productSpec, fileterByIsInStock );
        filteredProducts = filter(filteredProducts, productSpec, fileterByIsGlobalDistribution );
        filteredProducts = filter(filteredProducts, productSpec, fileterByIsGlobalBuy);
        filteredProducts.sort(comparatorByComments);
        filteredProducts.sort(comparatorBySaleVolume);
        filteredProducts.sort(comparatorByPrice);
        filteredProducts.sort(comparatorByCreateTime);
        return filteredProducts;
    }
    
    List<Product> filter(List<Product> products, Product productSpec, IFilter<Product,Product> filter) {
        List<Product> filteredProducts = new ArrayList<>();
        for (Product p : products) {
            if (filter.isMatch(p, productSpec))
            {
                filteredProducts.add((p));
            }
        }
        return filteredProducts;
    }
}

这个版本与版本三的主要区别是,采用匿名类,如果这些过滤器只在当前类中使用,那么,采用匿名类可以避免创建过多的 java 类。当你写版本三的方式多了之后,会尽量避免多写代码,而匿名类就是解决办法之一。 当然,匿名类也有缺点,比如理解难度也更加大一点,因为 IFilter 几乎是隐藏的。

第五版本

package com.example.test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class JDFilter {

    public static void main(String[] args) {

        Product p1 = new Product.Builder("1").salesVolume(1).comments(1).createTime(1)
                .price(1).isJDLogistic(true).isCashOnDelivery(true).isInStock(true)
                .isGlobalDistribution(true).isGlobalBuy(true).build();
        Product p2 = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        List<Product> products = new ArrayList<>();
        products.add(p1);
        products.add(p2);

    }

    List<Product> fileterByComparatorLambdaBase(List<Product> products, Product productSpec) {
        products.sort(Comparator.comparing((Product product) -> product.getCreateTime())
                .thenComparing((Product product) -> product.getSalesVolume())
                .thenComparing((Product product) -> product.getComments())
                .thenComparing((Product product) -> product.getPrice()));
        return products.stream().filter(product -> product.isGlobalDistribution())
                .filter(product -> product.isGlobalBuy() == productSpec.isGlobalBuy())
                .filter(product -> product.isInStock())
                .filter(product -> product.isCashOnDelivery())
                .filter(product -> product.isJDLogistic())
                .collect(Collectors.toList());
    }
}

更进一步,可以通过方法引用

package com.example.test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class JDFilter {

    public static void main(String[] args) {

        Product p1 = new Product.Builder("1").salesVolume(1).comments(1).createTime(1)
                .price(1).isJDLogistic(true).isCashOnDelivery(true).isInStock(true)
                .isGlobalDistribution(true).isGlobalBuy(true).build();
        Product p2 = new Product.Builder("2").salesVolume(2).comments(2).createTime(2)
                .price(2).isJDLogistic(false).isCashOnDelivery(false).isInStock(false)
                .isGlobalDistribution(false).isGlobalBuy(false).build();

        List<Product> products = new ArrayList<>();
        products.add(p1);
        products.add(p2);

    }

    List<Product> fileterByComparatorLambda(List<Product> products) {
        //方法引用
        products.sort(Comparator.comparing(Product::getCreateTime)
                .thenComparing(Product::getSalesVolume)
                .thenComparing(Product::getComments)
                .thenComparing(Product::getPrice));
        return products.stream().filter(product -> product.isGlobalDistribution())
                .filter(Product::isGlobalBuy)
                .filter(Product::isInStock)
                .filter(Product::isCashOnDelivery)
                .filter(Product::isJDLogistic)
                .collect(Collectors.toList());
    }
}

完成同样的功能,代码量,仅为开始的 1/3。而且更加易读和可维护。lambda 的力量可见一斑。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值