Convert a List to a Comma-Separated String in Java 8

迈不过友情╰ 2022-06-05 12:17 267阅读 0赞

Converting a List to a String with all the values of the List comma separated in Java 8 is really straightforward. Let’s have a look how to do that.
In Java 8

We can simply write String.join(..), pass a delimiter and an Iterable and the new StringJoiner will do the rest:

  1. List<String> cities = Arrays.asList("Milan",
  2. "London",
  3. "New York",
  4. "San Francisco");
  5. String citiesCommaSeparated = String.join(",", cities);
  6. System.out.println(citiesCommaSeparated);

//Output: Milan,London,New York,San Francisco

If we are working with stream we can write as follow and still have the same result:

  1. String citiesCommaSeparated = cities.stream()
  2. .collect(Collectors.joining(","));
  3. System.out.println(citiesCommaSeparated);

//Output: Milan,London,New York,San Francisco

Note: you can statically import java.util.stream.Collectors.joining if you prefer just typing “joining”.

In Java 7

For old times’ sake, let’s have a look at the Java 7 implementation:

  1. private static final String SEPARATOR = ",";
  2. public static void main(String[] args) {
  3. List<String> cities = Arrays.asList(
  4. "Milan",
  5. "London",
  6. "New York",
  7. "San Francisco");
  8. StringBuilder csvBuilder = new StringBuilder();
  9. for(String city : cities){
  10. csvBuilder.append(city);
  11. csvBuilder.append(SEPARATOR);
  12. }
  13. String csv = csvBuilder.toString();
  14. System.out.println(csv);

//OUTPUT: Milan,London,New York,San Francisco,

//Remove last comma

  1. csv = csv.substring(0, csv.length() - SEPARATOR.length());
  2. System.out.println(csv);

//OUTPUT: Milan,London,New York,San Francisco

As you can see it’s much more verbose and easier to make mistakes like forgetting to remove the last comma. You can implement this in several ways—for example by moving the logic that removes the last comma to inside the for-loop—but no implementation will be so explicative and easy to understand as the declarative solution expressed in Java 8.

Focus should be on what you want to do—joining a List of String—not on how.

Java 8: Manipulate String Before Joining

If you are using Stream, it’s really straightforward manipulate your String as you prefer by using map() or cutting some String out by using filter(). I’ll cover those topics in future articles. Meanwhile, this a straightforward example on how to transform the whole String to upper-case before joining.

Java 8: From List to Upper-Case String Comma Separated

  1. String citiesCommaSeparated = cities.stream()
  2. .map(String::toUpperCase)
  3. .collect(Collectors.joining(","));

//Output: MILAN,LONDON,NEW YORK,SAN FRANCISCO

https://dzone.com/articles/java-8-convert-list-to-string-comma-separated

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读