dcsimg
 

Formatting Output in Java

Monday May 10th 2021 by Sridhar M S
Article Image

This programming tutorial dives into how to format output in Java using Collectors.

Below is a sample program, written in Java, demonstrating how to use Java Collectors to format output. We also demonstrate how to use streams.

*/

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CollectorsJoiningEx 
{

	String delimiter = ", "; //Note that this is comma and followed by a space
	
	public static void main(String args[])
	{
		CollectorsJoiningEx collectorsJoiningEx = new CollectorsJoiningEx();
		collectorsJoiningEx.proceed();
	}

	public void proceed() {
		List numbers = Arrays.asList(5, 8, 11, 2);
		String delimiterSeparatedArrayValues = numbers.stream().map(index -> index.toString())
										.collect(Collectors.joining(delimiter));

		System.out.println("delimiterSeparatedArrayValues: " + delimiterSeparatedArrayValues);
	}
}

/*

Output:

$java CollectorsJoiningEx
delimiterSeparatedArrayValues: 5, 8, 11, 2
Home
Mobile Site | Full Site