Friday 4 November 2022

Get the string representation of array by given delimiter in Java

Write a method, that takes an array of any type and a delimeter, return the string representation of array elements.

 

Signature

String toString(Object[] array, String delimiter)

 

Find the below working application.

 


 

ArrayAsString.java

package com.sample.app.arrays;

import java.util.StringJoiner;

public class ArrayAsString {

	public static String toString(final Object[] array, final String delimeter) {

		if (array == null || array.length == 0) {
			return "";
		}

		String delimeterToApply = delimeter;
		if (delimeter == null || delimeter.isEmpty()) {
			delimeterToApply = ",";
		}

		final StringJoiner stringJointer = new StringJoiner(delimeterToApply);

		for (Object obj : array) {
			if (obj == null) {
				stringJointer.add("null");
			} else {
				stringJointer.add(obj.toString());
			}
		}

		return stringJointer.toString();
	}

	public static void main(String[] args) {
		System.out.println(toString(new Integer[] {}, null));
		System.out.println(toString(new Integer[] { 2, 3, 5 }, "-->"));
		System.out.println(toString(new Integer[] { 2, null, 3, null, 5 }, "-->"));
	}
}

Output

2-->3-->5
2-->null-->3-->null-->5



You may like

Interview Questions

Array programs in Java

Generic method to concatenate two arrays in Java

Constant folding in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

No comments:

Post a Comment