Java: convert List to a String

前端 未结 22 2625
日久生厌
日久生厌 2020-11-22 01:03

JavaScript has Array.join()

js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve

Does Java have anything

22条回答
  •  后悔当初
    2020-11-22 01:43

    With Java 8 you can do this without any third party library.

    If you want to join a Collection of Strings you can use the new String.join() method:

    List list = Arrays.asList("foo", "bar", "baz");
    String joined = String.join(" and ", list); // "foo and bar and baz"
    

    If you have a Collection with another type than String you can use the Stream API with the joining Collector:

    List list = Arrays.asList(
      new Person("John", "Smith"),
      new Person("Anna", "Martinez"),
      new Person("Paul", "Watson ")
    );
    
    String joinedFirstNames = list.stream()
      .map(Person::getFirstName)
      .collect(Collectors.joining(", ")); // "John, Anna, Paul"
    

    The StringJoiner class may also be useful.

提交回复
热议问题