How to Print List Items Without Brackets in Java?
Last Updated :
24 Oct, 2023
In Java, if you want to print the elements of a list without brackets [ ]. you need to manually iterate through the list and print each element separately. The brackets are automatically added when you directly print the entire list.
In this article, we will discuss how to print list items without brackets using Java.
Methods to Print List Items without Brackets
There are certain methods to Print list items without brackets mentioned below:
- Using a loop
- Using StringJoiner class
1. Using a Loop
We can print the elements of the list without brackets by using a loop to iterate through the list and print each element separately and this method allows you to have more control over the printing process and customize the output format as needed.
Below is the implementation of the above method:
Java
import java.io.*;
import java.util.Arrays;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
List<String> myList = Arrays.asList(
"Item-01" , "Item-02" , "Item-03" );
for (String item : myList) {
System.out.print(item + " " );
}
}
}
|
Output
Item-01 Item-02 Item-03
2. Using StringJoiner class
The StringJoiner class is a useful utility introduced in Java 8 for the concatenating strings with a specified delimiter and it provides a convenient way to join multiple string elements from list-like collection with a separator of your choice and the resulting string can be used to display output or construct more complex strings.
Below is the implementation of the above method:
Java
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
public class GFG {
public static void main(String[] args)
{
List<String> myList = Arrays.asList( "A" , "B" , "C" );
StringJoiner joiner = new StringJoiner( " " );
for (String item : myList)
joiner.add(item);
System.out.print(joiner.toString());
}
}
|
Share your thoughts in the comments
Please Login to comment...