/** * StringJoiner * @Author: Mr.li * @Date: 2020/9/8 */ @Test public void demo4() { List<String> names = new ArrayList<String>(); names.add("1"); names.add("2"); names.add("3"); System.out.println(String.join("-", names)); String[] arrStr = new String[]{"a", "b", "c"}; System.out.println(String.join("-", arrStr)); List<User> cr = new ArrayList<>(); User crd = new User(); crd.setContactRoleName("LEGAL"); User crd1 = new User(); 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 (User role : cr) { roleJoiner1.add(role.getContactRoleName()); } System.out.println("使用for循环时间拼接结果:" + roleJoiner1); }
result: