JAVA8 StringJoiner,String.join和StringBuffer 拼接字符串

使用StringJoiner 拼接:

		List cr = new ArrayList<>();
		ContactRoleAlternativeDetail crd = new ContactRoleAlternativeDetail();
		crd.setContactRoleName("LEGAL");
		ContactRoleAlternativeDetail crd1 = new ContactRoleAlternativeDetail();
		crd1.setContactRoleName("MAIN");
		cr.add(crd);
		cr.add(crd1);
		
		StringJoiner roleJoiner = new StringJoiner(",");//需要的间隔符
		// Lambda 实现拼接
		cr.forEach(role -> roleJoiner.add(role.getContactRoleName()));
		
		System.out.println("Lambda实现拼接结果:" + roleJoiner.toString());
		
		StringJoiner roleJoiner1 = new StringJoiner(",");//需要的间隔符
		for (ContactRoleAlternativeDetail role : cr) {
			roleJoiner1.add(role.getContactRoleName());
		}
		
		System.out.println("使用for循环时间拼接结果:" + roleJoiner1);

结果:


使用String.join 拼接:

List names=new ArrayList();
names.add("LEGAL");
names.add("MAIN");
names.add("CREATE");
System.out.println("List拼接" + String.join(",", names));
		
String[] arrStr=new String[]{"LEGAL","MAIN","CREATE"};
System.out.println("数组拼接" + String.join(",", arrStr));

结果:


使用StringBuffer 拼接:

		StringBuffer roleNames = new StringBuffer();  
		
		for (ContactRoleAlternativeDetail ca : cr) {
			if (roleNames.length( )== 0) {
				roleNames.append(ca.getContactRoleName());
			}else {
				roleNames.append(",");
				roleNames.append(ca.getContactRoleName());
			}
    	}
		
		
		System.out.println("StringBuffer实现拼接结果:" + roleNames.toString());

结果:


StringJoiner 其实也是基于StringBuilder实现的,所以效率还是比原始的+或者concat要高不少(在大量数据的情况下)。StringJoiner 因为是java8新加的,所以结合Lambda可以让代码更加简洁。

补充:
String.join源码中使用的是StringJoiner实现的,我看的比较浅显,发现如果是单个参数的list或者数组的话,String.join比StringJoiner更加优秀一些,代码更加简洁

你可能感兴趣的:(Java)