1. 简介

本文将介绍在Java中将List元素转换为String的几种常用方法。这种转换在调试或日志记录时特别有用,能以可读形式输出集合内容。

2. 使用List的toString()方法

最简单的方式是直接调用List的toString()方法:

@Test
public void whenListToString_thenPrintDefault() {
    List<Integer> intLIst = Arrays.asList(1, 2, 3);
 
    System.out.println(intLIst);
}

输出结果:

[1, 2, 3]

⚠️ 这种方式依赖List元素类型的toString()实现。如果使用自定义类型(如Person类),必须确保正确重写了toString()方法,否则会得到类似这样的垃圾输出:

[com.example.Person@1edf1c96, com.example.Person@368102c8, com.example.Person@6996db8]

3. 使用String.join()方法

String.join()方法可以用指定分隔符连接多个字符串:

3.1 处理字符串列表

@Test
public void whenStringJoinWithStringList_thenPrintCustom() {
    List<String> strList = Arrays.asList("one", "two", "three");
    System.out.println(String.join(" : ", strList));
}

输出:

one : two : three

3.2 处理非字符串列表

当List元素不是CharSequence子类时,需要先转换为字符串:

@Test
public void whenStringJoinWithNonStringList_thenPrintCustom() {
    List<Integer> intList = Arrays.asList(1, 2, 3);
    List<String> strList = intList.stream()
                                  .map(String::valueOf)
                                  .collect(Collectors.toList());
    System.out.println(String.join(" : ", strList));
}

输出:

1 : 2 : 3

✅ 这种方式通过Stream的map()collect()完成类型转换,但实际有更简洁的实现方式(见下节)。

4. 使用Collectors定制输出

当需要自定义输出格式时,Collectors.joining()是更好的选择:

@Test
public void whenCollectorsJoining_thenPrintCustom() {
    List<Integer> intList = Arrays.asList(1, 2, 3);
    String result = intList.stream()
                          .map(String::valueOf)
                          .collect(Collectors.joining("-", "{", "}"));
 
    System.out.println(result);
}

输出:

{1-2-3}

这种方式的优势:

  • 可指定分隔符(-
  • 可添加前缀({)和后缀(}
  • 适用于任何类型(只要能转为String)

5. 使用第三方库

Apache Commons Lang的StringUtils提供了更简洁的实现:

5.1 添加Maven依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

最新版本可在Maven中央仓库查询

5.2 实现代码

@Test
public void whenStringUtilsJoin_thenPrintCustom() {
    List<Integer> intList = Arrays.asList(1, 2, 3);
 
    System.out.println(StringUtils.join(intList, "|"));
}

输出:

1|2|3

⚠️ 同样依赖元素类型的toString()方法实现

6. 总结

本文介绍了四种将List转换为String的方法:

方法 适用场景 优点 缺点
toString() 快速调试 简单直接 格式固定
String.join() 字符串列表 语法简洁 需预转换类型
Collectors.joining() 定制格式 灵活可配置 需Stream操作
StringUtils.join() 通用场景 代码简洁 需第三方库

根据实际需求选择合适的方法:

  • 简单调试用toString()
  • 需要定制格式用Collectors.joining()
  • 项目已引入Commons Lang用StringUtils.join()
  • 纯字符串列表用String.join()最简单粗暴