java8 對list集合中的物件遍歷,重新賦值兩種方法,遍歷某個屬性返回陣列

愛~杦辷個訾發表於2020-01-11
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

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

/**
 * description: java8 對list集合中的物件遍歷,重新賦值兩種方法,遍歷某個屬性返回陣列
 * date: 2020/1/10 16:46
 * author:
 * version: 1.0
 */
@Slf4j
public class DaoThree {

    public static void main(String[] args) {
        List<FiveDao> list=new ArrayList<>();
        list.add(new FiveDao(10,"zhangming"));
        list.add(new FiveDao(12,"zhangsan"));
        list.add(new FiveDao(13,"lishi"));
        list.add(new FiveDao(11,"wangwu"));
        list.add(new FiveDao(14,"zhaoliu"));
        log.info("list:"+list);
        //方法一:
        list.forEach(p -> p.setName(UUID.randomUUID().toString().replaceAll("-", "")));
        log.info("list2:"+list);
        //方法二:會報錯 有時候會報錯,請使用方法一和三
//        list = list.stream().map(p -> p.setName(UUID.randomUUID().toString().replaceAll("-", "")) ).collect(Collectors.toList());
        //方法三:
        list=list.stream().map(detailVo -> {
            FiveDao detail = new FiveDao();
            BeanUtils.copyProperties(detailVo, detail);
            detail.setName(UUID.randomUUID().toString().replaceAll("-", ""));
            return detail;
        }).collect(Collectors.toList());
        log.info("list3:"+list);

        //遍歷某個屬性
        List<String> skuCodes=list.stream().map(FiveDao::getName).collect(Collectors.toList());
        log.info("skuCodes:"+skuCodes);
    }

}

相關文章