Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I join an array using Google Guava (Java)?

Tags:

java

guava

I am trying to join int[] (array of int) using Google Guava's Joiner class.

Example:

int[] array = { 1, 2, 3 };
String s = Joiner.on(", ").join(array);  // not allowed

I checked StackOverflow and Google. There is no "one-liner" in foundation classes to convert int[] to Integer[] or List<Integer>. It always requires a for loop, or your own hand-rolled helper function.

Any advice?

like image 201
kevinarpe Avatar asked Nov 22 '11 12:11

kevinarpe


People also ask

How do you join an array in Java?

To join elements of given string array strArray with a delimiter string delimiter , use String. join() method. Call String. join() method and pass the delimiter string delimiter followed by the string array strArray .

How do you combine numbers in an array in Java?

Example 1: Concatenate Two Arrays using arraycopy Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

How do you join numbers in Java?

int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7}; String result = StringUtils. join(ArrayUtils. toObject(arr), " - ");


1 Answers

Ints is a Guava library containing helper functions.

Given int[] array = { 1, 2, 3 } you can use the following:

String s = Joiner.on(", ").join(Ints.asList(array));

Or more succinctly:

String s = Ints.join(", ", array);
like image 178
Jens Hoffmann Avatar answered Sep 19 '22 05:09

Jens Hoffmann