java将集合里面的元素拼接为一条String字符串

java将集合里面的元素拼接为一条String字符串

1️⃣ 随便创建一个list集合,往里面塞入元素

2️⃣ 第一种方式:通过foreach循环实现

 但是通过这种方式只能将list集合里面的元素取出来变成一条string类型的字符串,不能根据自己的想法拼接

2️⃣ 第二种方式【推荐】:通过stream实现

 

 这种方式可以通过自己的想法,将集合里面的元素拼接成自己想要的形式

复制代码
package com.preciouslove.xinxin_emo.controller;


import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
 * @Author : YuanXin
 * @create 2023/4/6 16:49
 * @Description :
 */
public class Stream {

    public static void main(String[] args) {
        Stream stream = new Stream();
        stream.stream();
    }


    public void stream(){
        List<String> stringList = new ArrayList<>();
        stringList.add("A");
        stringList.add("B");
        stringList.add("C");
        stringList.add("D");
        stringList.add("E");
        stringList.add("F");
        stringList.add("G");

        StringBuilder stringBuilder = new StringBuilder();
        for (String value : stringList) {
            stringBuilder.append(value);
        }
        //System.out.println(stringBuilder);


        Optional<String> reduce =
                stringList.stream().sorted().reduce((s, s2) -> s + "," + s2);

        String value = reduce.get();
        System.out.println("stream:" + "\t" + value);



    }
}
复制代码

 

本文作者:$YX$

本文链接:https://www.cnblogs.com/preciouslove/p/17302908.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   $YX$  阅读(1605)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起