例如:有一个对象的一个字段是名字
现想把名字拼接成张三,李四,王五,... (拼接的前后是没有,号的)这样
有些人首先想到的就是使用for循环 加+号来实现 但是这样的代码看着不雅观
现在提供一种看着很高级的方式来实现(看着简洁,但是阅读性不强)
下面通过一段伪代码来实现
import java.util.*;
import java.util.stream.Collectors;
public class test {
/**分割符号 ',' 可根据需求自定义 */
private static final String COMMA = ",";
public static void main(String[] args) {
Student student1 = new Student("1","张三");
Student student2 = new Student("2","李四");
Student student3 = new Student("3","王五");
List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
String names =studentList.stream()
.map(Student::getName)
.collect(Collectors.joining(COMMA));
System.out.println(names);
}
}
class Student{
private String id;
private String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
效果展示: