Java8 stream().map.collect

一、背景

1)問題描述

假如存在對象數組A,包含一些屬性,現在需要給A加一些屬性,並輸出對象數組B,涉及到兩個知識點:①需要把A的對象挨個增加新的屬性②輸出B,則需要把A的屬性都複製到B

2)舉個栗子

有list對象數組A,有屬性userId和model,現在需要輸出對象數組B,數組B中包含所有A中的對象,但需要多一個屬性name

二、解決辦法

①把A的屬性複製過來
不能使用set方法一個一個複製,可以直接複製對象
BeanUtils.copyProperties(a, b);
②循環給B中的每個對象賦值name值
不能使用for循環遍歷A裏面的所有對象,那是java7的用法,java8用 stream().map.collect就可以了

List<B> listB = aList.stream().map(t->{
            B b = new B();
            String name;
            name = "XXXX";
            BeanUtils.copyProperties(a, b);
            b.setName(name);
            return b;
        }).collect(Collectors.toList());

我自己的源碼

public List<MobileList> queryMobile(){

        List<MobileInfo> mobileInfoList = mobileInfoMapper.queryMobileAll();
        List<MobileList> mobileLists= mobileInfoList.stream().map(t->{
            MobileList mobileList = new MobileList();
            String name;
            name = userInfoMapper.queryNameByUserId(t.getOwner());
            BeanUtils.copyProperties(t, mobileList);
            mobileList.setName(name);
            return mobileList;
        }).collect(Collectors.toList());
        return mobileLists;
    }

三、問題

第一次輸出mobileLists時候居然都是重複一模一樣的數據

四、問題原因

因爲stream().map.collect方法用的不對,MobileList mobileList = new MobileList();最新的對象應該在循環體內創建,而我之前是在循環體外創建的,導致循環輸出了最後一個對象。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章