Java Stream拼接字符串

时间:2025-02-21 13:13:21

实体类:
public class Fruits{
    private String name;
    private String weight;
 
    public Student(String weight, String name) {
        = weight;
        = name;
    }
 
    public String getWeight() {
        return weight;
    }
 
    public void setWeight(String weight) {
        = weight;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        = name;
    }
}

测试类:
import .*;
import ;
 
public class FruitsTestDemo{ 
    public static void main(String[] args) {
 
        Fruits fruits1= new Student("1.2","苹果");
        Fruits fruits2 = new Student("2.6","香蕉");
        Fruits fruits3 = new Student("3","葡萄");
 
        List<Fruits>  list = new ArrayList<>();
        list .add(fruits1);
        list .add(fruits2 );
        list .add(fruits3 );

        //用逗号拼接
        String names =list .stream()
                     .map(Fruits ::getName)
                     .collect((","));
        (names);

      //用双引号包裹和逗号隔开的格式拼接

      String names1 =list .stream()
                     .map(Fruits ::getName)
                     .collect(("\", \"", "\"", "\""));
        (names1);

    }
}