ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Converting a List to String in Java

2021-12-24 03:02:01  阅读:231  来源: 互联网

标签:Java String implementation List Person toString Converting method


https://www.baeldung.com/java-list-to-string

 

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

 

In this quick tutorial, we'll explain how to convert a List of elements to a String. This can be useful in certain scenarios, like printing the contents to the console in a human-readable form for inspection/debugging.

2. Standard toString() on a List

 

One of the simplest ways is to call the toString() method on the List:

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

Output:

[1, 2, 3]

This technique internally utilizes the toString() method of the type of elements within the List. In our case, we're using the Integer type, which has a proper implementation of the toString() method.

If we're using our custom type, such as Person, then we need to make sure that the Person class overrides the toString() method and doesn't rely on the default implementation. If we don't properly implement the toString() method, we might get unexpected results:

<iframe data-google-container-id="2" data-load-complete="true" frameborder="0" height="90" id="google_ads_iframe_/15184186,7114245/baeldung_leaderboard_mid_1_0" marginheight="0" marginwidth="0" name="google_ads_iframe_/15184186,7114245/baeldung_leaderboard_mid_1_0" scrolling="no" title="3rd party ad content" width="728"></iframe>
[org.baeldung.java.lists.ListToSTring$Person@1edf1c96,
  org.baeldung.java.lists.ListToSTring$Person@368102c8,
  org.baeldung.java.lists.ListToSTring$Person@6996db8]

3. Custom Implementation Using Collectors

 

Often, we might need to display the output in a different format.

Compared to the previous example, let's replace the comma (,) with a hyphen (-), and the square brackets ([, ]) with a set of curly braces ({, }):

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

Output:

{1-2-3}

The Collectors.joining() method requires a CharSequence, so we need to map the Integer to String. We can utilize this same idea with other classes, even when we don't have access to the code of the class.

4. Using an External Library

 

Now we'll use Apache Commons' StringUtils class to achieve similar results.

  SLING has Pro Football Ad by Sling TV    See More  

4.1. Maven Dependency

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

The latest version of the dependency can be found here.

4.2. Implementation

 

The implementation is literally a single method call:

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

Output:

1|2|3

Again, this implementation is internally dependent on the toString() implementation of the type we're considering.

5. Conclusion

 

In this article, we learned how easy it is to convert a List to a String using different techniques.

标签:Java,String,implementation,List,Person,toString,Converting,method
来源: https://www.cnblogs.com/kungfupanda/p/15725833.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有