java字符拼接成字符串_Java 拼接字符串的几种写法

用某个分隔符拼接字符串

写程序时经常遇到需要将集合的元素拼接成字符串,然后存入数据库的情况。

下边是我使用过的几种方式

使用流

StringBuilder

StringJoiner

Guava

代码

初始数据

List list = Arrays.asList("Luffy", "Zoro", "Nami",

"Usopp", "Sanji", "Chopper",

"Robin", "FRANKY", "BROOK");

1. 使用流

String result = list.stream().collect(Collectors.joining(","));

2. StringBuilder

StringBuilder strBur = new StringBuilder();

list.forEach(val -> {

strBur.append(val).append(",");

});

strBur.toString();

3. StringJoiner

StringJoiner strJor = new StringJoiner(",");

for(String str : list) {

strJor.add(str);

}

strJor.toString();

4. Guava

String result = Joiner.on(",").join(list);

性能测试

package com.cck;

import java.util.Arrays;

import java.util.List;

import java.util.StringJoiner;

import java.util.function.Consumer;

import java.util.stream.Collectors;

import com.google.common.base.Joiner;

public class Test {

// 1.使用流

public static Consumer> testStream() {

return (list) -> {

String result = list.stream().collect(Collectors.joining(","));

};

}

// 2.StringBuilder

public static Consumer> testStringBuilder() {

return (list) -> {

StringBuilder strBur = new StringBuilder();

list.forEach(val -> {

strBur.append(val).append(",");

});

strBur.toString();

};

}

// 3.StringJoiner

public static Consumer> testStringJoiner() {

return (list) -> {

StringJoiner strjor = new StringJoiner(",");

for(String str : list) {

strjor.add(str);

}

strjor.toString();

};

}

// 4.Guava

public static Consumer> testGuava() {

return (list) -> {

String result = Joiner.on(",").join(list);

};

}

public static void test(Consumer> consumer,

List list, String msg) {

long start = System.currentTimeMillis();

for (int i = 0; i < 1000000; i++) {

consumer.accept(list);

}

long end = System.currentTimeMillis();

System.out.println(msg + " need time : " + (end - start));

}

public static void main(String[] args) {

List list = Arrays.asList("Luffy", "Zoro", "Nami",

"Usopp", "Sanji", "Chopper",

"Robin", "FRANKY", "BROOK");

test(testStream(), list, "1.使用流");

test(testStringBuilder(), list, "2.StringBuilder");

test(testStringJoiner(), list, "3.StringJoiner");

test(testGuava(), list, "4.Guava");

}

}

执行100w次用时如下:

5b0f4fe73deceef95bc596c6e04b0065.png

执行10w次用时如下:

ac69d28c67198adf24f58288af297b27.png

感觉需要根据运算量去决定用哪种方法。

在没特别要求的情况下,自己还是使用Guava的多一些,因为看起来好看些。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值