java8 lambda小试牛刀,利用Stream把list转map,并将两个list的数据对象合并起来
public static void main(String[] args) {
// 集合1
List lists = new ArrayList<>();
SkillUpgrade s = new SkillUpgrade();
s.setLv(1);
s.setAppearNum(100);
lists.add(s);
SkillUpgrade s2 = new SkillUpgrade();
s2.setLv(2);
s2.setAppearNum(200);
lists.add(s2);
// 集合1
List listx = new ArrayList<>();
SkillUpgrade x = new SkillUpgrade();
x.setLv(1);
x.setSelectNum(1100);
listx.add(x);
SkillUpgrade x2 = new SkillUpgrade();
x2.setLv(2);
x2.setSelectNum(1200);
listx.add(x2);
// 把list转map,{k=lv,vaule=并为自身} . SkillUpgrade->SkillUpgrade或Function.identity()
Map map = listx.stream()
.collect(Collectors.toMap(SkillUpgrade::getLv, SkillUpgrade -> SkillUpgrade));
System.out.println("map:="+map);
// 合并
lists.forEach(n -> {
// 如果等级一致
if (map.containsKey(n.getLv())) {
SkillUpgrade obj = map.get(n.getLv());
// 把数量复制过去
n.setSelectNum(obj.getSelectNum());
}
});
System.out.println("lists:="+lists);
// 重复问题
Map keyRedo = listx.stream()
.collect(Collectors.toMap(SkillUpgrade::getLv, Function.identity(), (key1, key2) -> key2));
// 方式二:指定实例的map
Map linkedHashMap = listx.stream().collect(Collectors.toMap(SkillUpgrade::getLv,
SkillUpgrade -> SkillUpgrade, (key1, key2) -> key2, LinkedHashMap::new));
}
/**
* output:map:={1=SkillUpgrade [skillId=null, skillName=null, lv=1, persNum=null, selectNum=1100, appearNum=null], 2=SkillUpgrade [skillId=null, skillName=null, lv=2, persNum=null, selectNum=1200, appearNum=null]}
* lists:=[SkillUpgrade [skillId=null, skillName=null, lv=1, persNum=null, selectNum=1100, appearNum=100], SkillUpgrade [skillId=null, skillName=null, lv=2, persNum=null, selectNum=1200, appearNum=200]]
*/
map:={1=SkillUpgrade [skillId=null, skillName=null, lv=1, persNum=null, selectNum=1100, appearNum=null], 2=SkillUpgrade [skillId=null, skillName=null, lv=2, persNum=null, selectNum=1200, appearNum=null]}
lists:=[SkillUpgrade [skillId=null, skillName=null, lv=1, persNum=null, selectNum=1100, appearNum=100], SkillUpgrade [skillId=null, skillName=null, lv=2, persNum=null, selectNum=1200, appearNum=200]]