欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 8 stream 实战案例

程序员文章站 2022-06-09 12:51:23
...
Map<String, Phone> mapk = phonel.stream().collect(Collectors.toMap(Phone::getName, student -> student));
		List<User> usrList = userl.stream().map(o->{ return toFamily(mapk.get(o.getUsrname()),o);}).collect(Collectors.toList());
		usrList.stream().forEach(o-> {System.out.println(o.getPhone().getNum());});

以上代码留着备用。用流的方式 对两个集合做合并  因为是demo 随便写的对象 一个User 一个Phone  场景就是 根据两个对象的关联键 一一配对。最终返回 user 集合 。user 中包含Phone     单个属性赋值一个道理。

 

好处就是 之前要写很多很多行的代码。。现在两行搞定了。。确实比较好用。

package com.zccpro.demo;

public class User {

	private String usrname;
	
	private String passwd;
	
	private Phone phone;
	
	

	public Phone getPhone() {
		return phone;
	}

	public void setPhone(Phone phone) {
		this.phone = phone;
	}

	public String getUsrname() {
		return usrname;
	}

	public void setUsrname(String usrname) {
		this.usrname = usrname;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	
	
}
package com.zccpro.demo;

public class Phone {

	private String name;
	
	private String num;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getNum() {
		return num;
	}

	public void setNum(String num) {
		this.num = num;
	}
	
	
}
package com.zccpro.demo;

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

public class CollectionTest {

	public static void main(String[] args) {
		ArrayList<User> userl = new ArrayList<User>();
		ArrayList<Phone> phonel = new ArrayList<Phone>();
		User user = new User();
		user.setPasswd("p1");
		user.setUsrname("u1");
		
		User user2 = new User();
		user2.setPasswd("p2");
		user2.setUsrname("u2");
		userl.add(user);
		userl.add(user2);
		Phone phone = new Phone();
		phone.setName("u1");
		phone.setNum("1");
		Phone phone2 = new Phone();
		phone2.setName("u2");
		phone2.setNum("2");
		phonel.add(phone);
		phonel.add(phone2);
		
		Map<String, Phone> mapk = phonel.stream().collect(Collectors.toMap(Phone::getName, student -> student));
		List<User> usrList = userl.stream().map(o->{ return toFamily(mapk.get(o.getUsrname()),o);}).collect(Collectors.toList());
		usrList.stream().forEach(o-> {System.out.println(o.getPhone().getNum());});
		
	}
	
	private static User toFamily(Phone phone, User usr) {
       usr.setPhone(phone);
        return usr;
    }

}

参考别人的代码写的demo 实际可用。。。自己跑一跑 学的更快

后来实际写业务时 代码稍作了修改 如下

usrList = userl.stream().map(o->{o.setPhone(mapk.get(o.getUsrname()));return o;}).collect(Collectors.toList());