1、Collectors.joining()提供了多个入参,可以指定分隔符及开头结尾字符串。
2、需要保证流最后join的数据类型是字符串,如果不是正常加个.map(String::valueOf)即可。
public class Test {
public static void main(String[] args) {
List<User> list = Arrays.asList(
new User("小赵", "男",20, new BigDecimal("123.33"), DateUtil.parseDateTime("2014-5-18 23:12:29")),
new User("小钱", "女",9, new BigDecimal("89.12"), DateUtil.parseDateTime("2023-2-18 06:45:12")),
new User("小孙", "女",18, new BigDecimal("280.28"), DateUtil.parseDateTime("2009-3-31 16:33:45")),
new User("小李", "男",13, new BigDecimal("1000.99"), DateUtil.parseDateTime("1992-12-4 10:48:08"))
);
list.forEach(System.out::println);
System.out.println();
String nameStr1 = list.stream().map(User::getName).collect(Collectors.joining());
System.out.println(nameStr1);
String nameStr2 = list.stream().map(User::getName).collect(Collectors.joining("-"));
System.out.println(nameStr2);
String nameStr3 = list.stream().map(User::getName).collect(Collectors.joining("-", "(", ")"));
System.out.println(nameStr3);
String ageStr = list.stream().map(User::getAge).map(String::valueOf).collect(Collectors.joining("、"));
System.out.println(ageStr);
}
}
@Data
@ToString
@AllArgsConstructor
class User {
private String name;
private String sex;
private Integer age;
private BigDecimal money;
private Date birthday;
}
User(name=小赵, sex=男, age=20, money=123.33, birthday=2014-05-18 23:12:29)
User(name=小钱, sex=女, age=9, money=89.12, birthday=2023-02-18 06:45:12)
User(name=小孙, sex=女, age=18, money=280.28, birthday=2009-03-31 16:33:45)
User(name=小李, sex=男, age=13, money=1000.99, birthday=1992-12-04 10:48:08)
小赵小钱小孙小李
小赵-小钱-小孙-小李
(小赵-小钱-小孙-小李)
20、9、18、13