How to use Stream API In Java
Stream API was introduced in Java 8 and is used to process collections of objects. The joining() method of Collectors Class, in Java, is used to join various elements of a character or string array into a single string object.
Example
Java
// Java Program to Convert ArrayList to // Comma Separated String // Using Stream API // Importing required classes import java.util.*; import java.util.stream.Collectors; // Main class public class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geeklist = new ArrayList<String>(); // Adding elements to above ArrayList // using add() method geeklist.add( "welcome" ); geeklist.add( "to" ); geeklist.add( "geeks" ); geeklist.add( "for" ); geeklist.add( "geeks" ); // collect() method returns the result of the // intermediate operations performed on the stream String str = geeklist.stream().collect( Collectors.joining( "," )); // Printing the comma separated string System.out.println(str); } } |
welcome,to,geeks,for,geeks
Convert ArrayList to Comma Separated String in Java
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. In order to convert ArrayList to a comma-separated String, these are the approaches available in Java as listed and proposed below as follows:
Earlier before Java 8 there were only standard methods available in order for this conversion but with the introduction to the concept of Streams and Lambda, new methods do arise into play of which are all listed below:
- Using append() method of StringBuilder
- Using toString() method
- Using Apache Commons StringUtils class
- Using Stream API
- Using String join() method of String class
Let us discuss each of the above methods proposed to deeper depth alongside programs to get a deep-dive understanding as follows:
Contact Us