• Java8-Guava实战示例


     

    示例一:

    跟示例三对比一下,尽量用示例三

    List<InvoiceQueryBean> invoiceQueryBeanList = new ArrayList<>();
    List<String> invoices = Lists.newArrayList(Iterators.transform(
            invoiceQueryBeanList.iterator(), new Function<InvoiceQueryBean, String>() {
        @Nullable
        @Override
        public String apply(@Nullable InvoiceQueryBean input) {
            if (StringUtils.isNotBlank(input.getLoanInvoiceId())) {
                return input.getLoanInvoiceId();
            } else {
                return null;
            }
        }
    }));
    //去除空的 Iterators.removeIf(invoices.iterator(), StringUtils::isBlank);

    示例二:

    public static List<PersonLoanInvoiceQueryPojo> getInvoiceQueryPojoList(List<InvoiceQueryBean> invoiceQueryBean) {
        return Lists.newArrayList(Iterators.transform(invoiceQueryBean.iterator(),
                input -> input == null ? null :
                        PersonLoanInvoiceQueryPojo.Builder.getInstance()
                                .addLoanInvoiceId(input.getLoanInvoiceId())
                                .addUserName(input.getUserName())
                                .addCertificateKind(input.getCertificateKind())
                                .addCertificateNo(input.getCertificateNo()).addProductName(input.getProductName())
                                .addMerchantName(input.getMerchantName())
                                .addStoreName(input.getStoreName())
                                .addApplyDate(input.getApplyDate()).addLoanAmount(input.getLoanAmount())
                                .addLoanPeriod(input.getLoanPeriod()).addLoanPurpose(input.getLoanPurpose())
                                .addLoanDate(input.getLoanDate()).addRate(input.getRate())
                                .addChannelNo(input.getChannelNo())
                                .addApproveDate(input.getApproveDate())
                                .addReply(input.getReply())
                                .addMarketingCenterId(input.getMarketingCenterId()).build()));
    }
    public class PersonLoanInvoiceQueryPojo implements Serializable{
        
        private static final long serialVersionUID = -408985049449365784L;
    
        private String loanInvoiceId;
        
        private String userId;
        
        private String userName;
    
        public static class Builder {
            private PersonLoanInvoiceQueryPojo instance = new PersonLoanInvoiceQueryPojo();
    
            private Builder(){}
    
            public static Builder getInstance() {
                return new Builder();
            }
    
            public static Builder getInstance(PersonLoanInvoiceQueryPojo instance){
                Builder builder = new Builder();
                builder.instance = instance;
                return builder;
            }
    
            public Builder addLoanInvoiceId(String loanInvoiceId) {
                this.instance.setLoanInvoiceId(loanInvoiceId);
                return this;
            }
    
            public Builder addUserId(String userId) {
                this.instance.setUserId(userId);
                return this;
            }
    
            public Builder addUserName(String userName) {
                this.instance.setUserName(userName);
                return this;
            }
    
            public PersonLoanInvoiceQueryPojo build() {
                return this.instance;
            }
    
        }
        
        setters();&getters();
    }

     示例三:方法引用

      方法引用主要有三类:

        (1)指向静态方法的方法引用,(例如:Integer中的parseInt方法,写作Integer::parseInt

        (2)指向任意类型实例方法的方法引用(例如String中的length方法,写作String::length

        (3)指向现有对象的实例方法的方法引用(如下例)

    import com.google.common.collect.Iterators;
    import com.google.common.collect.Lists;
    
    List<CreditPersonalInfoChangeApplySerial> applySerialList = new ArrayList<>();
    List<String> operatorNoList = Lists.newArrayList(
                Iterators.transform(applySerialList.iterator(), CreditPersonalInfoChangeApplySerial::getOperatorNo)); //这个叫做lambda的方法引用,注意方法引用的这个方法不需要()

     示例四:

      Lambad将List转换成Map

    import com.google.common.collect.Maps;
    
    List<QueryUserAppInfoByUserIdListPojo> operatorInfoList = new ArrayList<>();
    Map<String, QueryUserAppInfoByUserIdListPojo> operatorMap
                = Maps.uniqueIndex(operatorInfoList.iterator(), QueryUserAppInfoByUserIdListPojo::getUserId);
                
    public class QueryUserAppInfoByUserIdListPojo implements Serializable {
        private static final long serialVersionUID = 6876288995978264269L;
        private String userId;
        
        public String getUserId() {
            return this.userId;
        }
    
        public void setUserId(String userId) {
            this.userId = userId;
        }
    
    }

     示例五:

    List<UserPojo> list =  new ArrayList<>();
    list.forEach(input -> {
        if (input.getCertificateKind().equals(EnumCertificateKind.RESIDENT_IDENTITY_CARD)) {
            userCertificateMap.put(pojo.getUserId(), input);
        }
    });

     示例六:

      遍历的时候需要使用到元素的索引,很可惜,Java8 的 Iterable 并没有提供一个带索引的 forEach 方法,自动动手写一个满足自己的需求。

    import java.util.Objects;
    import java.util.function.BiConsumer;
    
    /**
     * Iterable 的工具类
     */
    public class Iterables {
    
        public static <E> void forEach(
                Iterable<? extends E> elements, BiConsumer<Integer, ? super E> action) {
            Objects.requireNonNull(elements);
            Objects.requireNonNull(action);
    
            int index = 0;
            for (E element : elements) {
                action.accept(index++, element);
            }
        }
    }
    public static void main(String[] args) throws Exception {
    
        List<String> list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g");
    
        Iterables.forEach(list, (index, str) -> System.out.println(index + " -> " + str));
    }

     示例七:Iterators.find

    注意:find()函数有两个重载方法,其中一个是带 defaultValue 的,注意如果别迭代的集合没有符合条件的数据的话,一定要定义一个默认值。否则会报NoSuchElementException异常

    Iterators.find(pojoList.iterator(), input -> input != null, null);

    参考:

  • 相关阅读:
    [整理] jQuery插件开发
    windows2008r2安装笔记
    javascript 中 typeof 和 instanceof 的区别
    mysql 复制表结构和表数据
    一个例子明白 javascript 中 for 与 for in 的区别
    实现自己的框架
    Jenkins 前端项目构建报错:Vue packages version mismatch
    linux Auditd 审计工具安装报错
    linux定时压缩日志文件脚本
    Robot Framework 3.1.2 执行测试用例报错
  • 原文地址:https://www.cnblogs.com/happyflyingpig/p/9004534.html
Copyright © 2020-2023  润新知