Monday, 3 October 2016

How to join array elements with Separator in Java?

In some scenarios, if we need to join elements of array or collections i.e opposite to split, then there are various approaches to achieve the same. These joined elements can be used in database queries.

Lets take one common scenario.

Suppose we have an array of Strings and we need to pass all the elements in IN statement of a SQL query to retrieve the result. For this particular case we need to join the Strings with separators, as we cannot directly pass the String array.

Lets take an example, suppose we have a String array arr and we need to pass the elements of array in IN statement of a SQL query.

String[] arr = new String[] { "a", "b", "c" };


So we cannot directly pass the above array elements in IN statement, as the above format for passing Strings in IN statement is not allowed. In this case we need to join all the elements to make a single String with some separators before passing it to query.


For this we can use Apache StringUtils.join() method to join elements of an Array with separators. But in Java 8, we can achieve the same using String.join() method of String class instead of using Apache StringUtils class.


public static void joinElements() {

// directly specifying the elements
String joined1 = String.join("','", "a", "b", "c");
StringBuilder st1 = new StringBuilder(); st1.append("'");
st1.append(joined1);
st1.append("'");
System.out.println(st1.toString());

// using arrays
String[] array = new String[] { "a", "b", "c" };
StringBuilder st2 = new StringBuilder();
st2.append("'");
String joined2 = String.join("','", array);
st2.append(joined2);
st2.append("'");
System.out.println(st2.toString());

// using iterables
List<String> list = Arrays.asList(array);
String joined3 = String.join("','", list);
StringBuilder st3 = new StringBuilder();
st3.append("'");
st3.append(joined3);
st3.append("'");
System.out.println(st3.toString());

// using iterables
list = Arrays.asList(array);
String joined4 = String.join("','", list);
StringBuilder st4 = new StringBuilder();
st4.append("'");
st4.append(joined4);
st4.append("'");
System.out.println(st4.toString());

}

Output -

'a','b','c'
'a','b','c'
'a','b','c'
'a','b','c'


As we have joined the elements of array to make a single String, now we can pass the String in IN statement of SQL query.



No comments:

Post a Comment