Skip to content

Stream的使用

使用Stream替代switch

项目: misszb/CouponStatus

Stream的特性、用法、stream().map().collect()用法

需求

将枚举值转换成对应的枚举类型

实现

第一种写法:使用switch

java
public static CouponStatus toType(int value) {
    CouponStatus type = null;
    switch (value) {
        case 1:
            type = AVAILABLE;
            break;
        case 2:
            type = USED;
            break;
        case 3:
            type = EXPIRED;
            break;
        }
    return type;
}

缺点:如果枚举值很多,需要进行的判断多

第二种写法:使用Stream

java
public static CouponStatus toType(int value) {
    // CouponStatus的values进行流处理
    return Stream.of(CouponStatus.values())
             // 过滤value相等的数据
             .filter(c -> c.value == value)
             // 返回任意一条数据
             .findAny()
             // 如果没有符合条件的值,就返回null
             .orElse(null);
}

使用Stream对List数据进行处理

项目: misszb/CouponPureVO

需求

从数据库查询出List数据,对数据进行过滤后返回前端

分析

第一、新建一个vo类,定义需要返回的字段

第二、将List数据赋值到vo字段

常用的方法是遍历List数据

现在可以使用Stream

实现

java
package com.zb.misszb.vo;

import com.zb.misszb.model.Coupon;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
@NoArgsConstructor
public class CouponPureVO {
    private Long id;
    private String title;
    private Date startTime;
    private Date endTime;
    private String description;
    private BigDecimal fullMoney;
    private BigDecimal minus;
    private BigDecimal rate;
    private Integer type;
    private String remark;
    private Boolean wholeStore;

    public CouponPureVO(Coupon coupon){
        BeanUtils.copyProperties(coupon, this);
    }

    public static List<CouponPureVO> getList(List<Coupon> couponList) {
        return couponList.stream()
                .map(CouponPureVO::new)
                .collect(Collectors.toList());
    }
}

总结

java
couponList.stream().map(CouponPureVO::new).collect(Collectors.toList());

couponList是查询出的数据

map()用户映射每个元素到对应的结果,可以传入具体的执行方法,当前传入的是CouponPureVO类的构造方法,具体执行的是public CouponPureVO(Coupon coupon)这个方法(将 值拷贝到CouponPureVO定义的字段上)

collect(Collectors.toList())返回List

如有转载或 CV 的请标注本站原文地址