List提取对象某一个属性,List转String字符串拼接
List提取对象内的某一属性,不用for循环写法
public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User("张三",1,20));
users.add(new User("李四",1,18));
users.add(new User("韩梅梅",0,19));
users.add(new User("王五",1,22));
System.out.println(users);
// 获取姓名list
List<String> names = getName(users);
System.out.println(names);
// 姓名拼接成字符串
String nameStr = list2String(names);
System.out.println(nameStr);
}
/**
* 提取姓名
* @return
*/
private static List<String> getName(List<User> list){
return list.stream().map(User::getName).collect(Collectors.toList());
}
List将姓名拼接,适用于sql值拼接
private static String list2String(List<String> list) {
return list.stream().map(str -> "'" + str + "'").collect(Collectors.joining(","));
}
打印结果