使用场景:用某个分隔符拼接字符串
- 下边是我使用过的几种方式
- 废话不多说,直接上代码
- 初始数据
- 1.使用流
- 2.StringBuilder
- 3.[StringJoiner](https://blog.csdn.net/qq_43417581/article/details/126076152?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170478446616800186556680%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=170478446616800186556680&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-2-126076152-null-null.142^v99^pc_search_result_base6&utm_term=StringJoiner&spm=1018.2226.3001.4187) (详情请点击,看的大佬的)
- 4. Guava
- 做一个性能测试
- 执行10w次用时比较如下:
- 执行100w次用时比较如下:
下边是我使用过的几种方式
- 使用流
- StringBuilder
- StringJoiner
- Guava
当然,肯定要看业务场景来选择适当的方法,这里小编为大家做过性能测试。
废话不多说,直接上代码
初始数据
List<String> 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<List<String>> testStream() { return (list) -> { String result = list.stream().collect(Collectors.joining(",")); }; } // 2.StringBuilder public static Consumer<List<String>> testStringBuilder() { return (list) -> { StringBuilder strBur = new StringBuilder(); list.forEach(val -> { strBur.append(val).append(","); }); strBur.toString(); }; } // 3.StringJoiner public static Consumer<List<String>> testStringJoiner() { return (list) -> { StringJoiner strjor = new StringJoiner(","); for(String str : list) { strjor.add(str); } strjor.toString(); }; } // 4.Guava public static Consumer<List<String>> testGuava() { return (list) -> { String result = Joiner.on(",").join(list); }; } public static void test(Consumer<List<String>> consumer, List<String> 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<String> 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"); } }
执行10w次用时比较如下:
执行100w次用时比较如下:
感觉需要根据运算量去决定用哪种方法。
在没特别要求的情况下,自己还是使用Guava的多一些,因为看起来好看些。