zoukankan      html  css  js  c++  java
  • Converting a List to String in Java

    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:

    [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.

    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.

    What Doesn't Kill Me Makes Me Stronger
  • 相关阅读:
    Java学习笔记——动态代理
    Java学习随笔——RMI
    数据结构与算法——排序算法
    设计模式——装饰者模式
    Struts2中使用execAndWait后,在 Action中调用getXXX()方法报告java.lang.NullPointerException异常的原因和解决方法
    vs中debug的一个小技巧 -- debug时忽略某段代码
    SilverlightMVVM模式中的数据校验
    技能图谱
    MQ队列管理器损坏的处理方法
    informix数据库锁表处理方法
  • 原文地址:https://www.cnblogs.com/kungfupanda/p/15725833.html
Copyright © 2011-2022 走看看