Given a list
List<String> l = new ArrayList<String>();
l.add("one");
l.add("two");
l.add("three");
I have a method
String join(List<String> messages) {
if (messages.isEmpty()) return "";
if (messages.size() == 1) return messages.get(0);
String message = "";
message = StringUtils.join(messages.subList(0, messages.size() -2), ", ");
message = message + (messages.size() > 2 ? ", " : "") + StringUtils.join(messages.subList(messages.size() -2, messages.size()), ", and ");
return message;
}
which, for l, produces "one, two, and three".
My question is, is there a standard (apache-commons) method that does the same?, eg
WhatEverUtils.join(l, ", ", ", and ");
To clarify. My problem is not getting this method to work. It works just as I want it to, it's tested and all is well. My problem is that I could not find some apache-commons-like module which implements such functionality. Which surprises me, since I cannot be the first one to need this.
But then maybe everyone else has just done
StringUtils.join(l, ", ").replaceAll(lastCommaRegex, ", and");
In Java 8 you can use String.join() like following:
Collection<String> elements = ....;
String result = String.join(", ", elements);
What about join from:
org.apache.commons.lang.StringUtils
Example:
StringUtils.join(new String[] { "one", "two", "three" }, ", "); // one, two, three
To have "and" or ", and" you can simple replace the last comma.
With Java 8, you can use streams with joiners.
Collection<String> strings;
...
String commaDelimited = strings.stream().collect(Collectors.joining(","));
// use strings.parallelStream() instead, if you think
// there are gains to be had by doing fork/join
I like using Guava for this purpose. Neat and very useful:
Joiner.on(",").join(myList)
This kind of code has been written time and time again and you should rather be freed implementing your specific implementation logic.
If you use maven, herewith the dependency:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
It has a bunch of other wonderful cool features too!
This will produce the string "one, two, and three".
List<String> originalList = Arrays.asList("one", "two", "three");
Joiner.on(", ")
.join(originalList.subList(0, originalList.size() - 1))
.concat(", and ")
.concat(originalList.get(originalList.size() - 1));
To produce grammatical output in English there are 3 cases to consider when concatenating a list of strings:
"A"
"A and B"
"A, B, and C.
This can be accomplished using standard Java or Guava like below. The solutions are basically the same and just up to preference what you want to use.
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class JoinListTest {
#Test
public void test_join() {
// create cases (don't need to use ImmutableList builder from guava)
final List<String> case1 = new ImmutableList.Builder<String>().add("A").build();
final List<String> case2 = new ImmutableList.Builder<String>().add("A", "B").build();
final List<String> case3 = new ImmutableList.Builder<String>().add("A", "B", "C").build();
// test with standard java
assertEquals("A", joinListGrammaticallyWithJava(case1));
assertEquals("A and B", joinListGrammaticallyWithJava(case2));
assertEquals("A, B, and C", joinListGrammaticallyWithJava(case3));
// test with guava
assertEquals("A", joinListGrammaticallyWithGuava(case1));
assertEquals("A and B", joinListGrammaticallyWithGuava(case2));
assertEquals("A, B, and C", joinListGrammaticallyWithGuava(case3));
}
private String joinListGrammaticallyWithJava(final List<String> list) {
return list.size() > 1
? String.join(", ", list.subList(0, list.size() - 1))
.concat(String.format("%s and ", list.size() > 2 ? "," : ""))
.concat(list.get(list.size() - 1))
: list.get(0);
}
private String joinListGrammaticallyWithGuava(final List<String> list) {
return list.size() > 1
? Joiner.on(", ").join(list.subList(0, list.size() - 1))
.concat(String.format("%s and ", list.size() > 2 ? "," : ""))
.concat(list.get(list.size() - 1))
: list.get(0);
}
}
Other answers talk about "replacing the last comma", which isn't safe in case the last term itself contains a comma.
Rather than use a library, you can just use one (albeit long) line of JDK code:
public static String join(List<String> msgs) {
return msgs == null || msgs.size() == 0 ? "" : msgs.size() == 1 ? msgs.get(0) : msgs.subList(0, msgs.size() - 1).toString().replaceAll("^.|.$", "") + " and " + msgs.get(msgs.size() - 1);
}
See a live demo of this code handling all edge cases.
FYI, here's a more readable two-liner:
public static String join(List<String> msgs) {
int size = msgs == null ? 0 : msgs.size();
return size == 0 ? "" : size == 1 ? msgs.get(0) : msgs.subList(0, --size).toString().replaceAll("^.|.$", "") + " and " + msgs.get(size);
}
I don't know any Apache String joiner that can support adding and in the joined String.
Here's an untested code that will do what you asked:
public static String join(String separator, List<String> mList, boolean includeAndInText) {
StringBuilder sb = new StringBuilder();
int count = 0;
for (String m: mList) {
if (includeAndInText && (count + 1 != mList.size())) {
sb.append (" and ");
}
sb.append(m);
count++;
if (count < mList.size()) {
sp.append(separator);
}
}
return sb.toString();
}
If you want a more comprehensive solution, there is a brilliant NLG library for that - SimpleNLG
//initialize
NLGFactory nlgFactory = new NLGFactory(Lexicon.getDefaultLexicon());
Realiser realiser = new Realiser(lexicon);
CoordinatedPhraseElement cp = nlgFactory.createCoordinatedPhrase();
cp.setConjunction("and");
//code begins here
List<String> l = new ArrayList<String>();
l.add("one");
l.add("two");
l.add("three");
l.forEach(cp::addCoordinate);
//output
String output = realiser.realise(cp).toString();
This can support any number of array elements without needing to do ugly hacks like "remove last comma".
Improved version from Bohemian♦'s answer. You can choose to remove the nulled items check on personal preferences.
/** Auto Concat Wrapper
* Wraps a list of string with comma and concat the last element with "and" string.
* E.g: List["A", "B", "C", "D"] -> Output: "A, B, C and D"
* #param elements
*/
public static String join(List<String> elements){
if(elements==null){return "";}
List<String> tmp = new ArrayList<>(elements);
tmp.removeAll(Collections.singleton(null)); //Remove all nulled items
int size = tmp.size();
return size == 0 ? "" : size == 1 ? tmp.get(0) : String.join(", ", tmp.subList(0, --size)).concat(" and ").concat(tmp.get(size));
}
Test results:
List<String> w = Arrays.asList("A");
List<String> x = Arrays.asList("A", "B");
List<String> y = Arrays.asList("A", "B", null, "C");
List<String> z = Arrays.asList("A", "B", "C", "D");
System.out.println(join(w));//A
System.out.println(join(x));//A and B
System.out.println(join(y));//A, B and C
System.out.println(join(z));//A, B, C and D
In this way we can join
List<Long> ids = new ArrayList<>();
String idsAsString = String.join(",", ids);
System.out.println(idsAsString);
Related
I want the Java code for converting an array of strings into an string.
Java 8+
Use String.join():
String str = String.join(",", arr);
Note that arr can also be any Iterable (such as a list), not just an array.
If you have a Stream, you can use the joining collector:
Stream.of("a", "b", "c")
.collect(Collectors.joining(","))
Legacy (Java 7 and earlier)
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
Alternatively, if you just want a "debug-style" dump of an array:
String str = Arrays.toString(arr);
Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer.
Android
Use TextUtils.join():
String str = TextUtils.join(",", arr);
General notes
You can modify all the above examples depending on what characters, if any, you want in between strings.
DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.
Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:
String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);
Produces:
a-b-1
I like using Google's Guava Joiner for this, e.g.:
Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");
would produce the same String as:
new String("Harry, Ron, Hermione");
ETA: Java 8 has similar support now:
String.join(", ", "Harry", "Ron", "Hermione");
Can't see support for skipping null values, but that's easily worked around.
From Java 8, the simplest way I think is:
String[] array = { "cat", "mouse" };
String delimiter = "";
String result = String.join(delimiter, array);
This way you can choose an arbitrary delimiter.
You could do this, given an array a of primitive type:
StringBuffer result = new StringBuffer();
for (int i = 0; i < a.length; i++) {
result.append( a[i] );
//result.append( optional separator );
}
String mynewstring = result.toString();
Try the Arrays.deepToString method.
Returns a string representation of the "deep contents" of the specified
array. If the array contains other arrays as elements, the string
representation contains their contents and so on. This method is
designed for converting multidimensional arrays to strings
Try the Arrays.toString overloaded methods.
Or else, try this below generic implementation:
public static void main(String... args) throws Exception {
String[] array = {"ABC", "XYZ", "PQR"};
System.out.println(new Test().join(array, ", "));
}
public <T> String join(T[] array, String cement) {
StringBuilder builder = new StringBuilder();
if(array == null || array.length == 0) {
return null;
}
for (T t : array) {
builder.append(t).append(cement);
}
builder.delete(builder.length() - cement.length(), builder.length());
return builder.toString();
}
public class ArrayToString
{
public static void main(String[] args)
{
String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};
String newString = Arrays.toString(strArray);
newString = newString.substring(1, newString.length()-1);
System.out.println("New New String: " + newString);
}
}
You want code which produce string from arrayList,
Iterate through all elements in list and add it to your String result
you can do this in 2 ways: using String as result or StringBuffer/StringBuilder.
Example:
String result = "";
for (String s : list) {
result += s;
}
...but this isn't good practice because of performance reason. Better is using StringBuffer (threads safe) or StringBuilder which are more appropriate to adding Strings
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';
String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s
result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s
result = String.join("", strings);
//Java 8 .join: 3ms
Public String join(String delimiter, String[] s)
{
int ls = s.length;
switch (ls)
{
case 0: return "";
case 1: return s[0];
case 2: return s[0].concat(delimiter).concat(s[1]);
default:
int l1 = ls / 2;
String[] s1 = Arrays.copyOfRange(s, 0, l1);
String[] s2 = Arrays.copyOfRange(s, l1, ls);
return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
}
}
result = join("", strings);
// Divide&Conquer join: 7ms
If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.
String array[]={"one","two"};
String s="";
for(int i=0;i<array.length;i++)
{
s=s+array[i];
}
System.out.print(s);
Use Apache Commons' StringUtils library's join method.
String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");
When we use stream we do have more flexibility, like
map --> convert any array object to toString
filter --> remove when it is empty
join --> Adding joining character
//Deduplicate the comma character in the input string
String[] splits = input.split("\\s*,\\s*");
return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors.joining(", "));
If you know how much elements the array has, a simple way is doing this:
String appendedString = "" + array[0] + "" + array[1] + "" + array[2] + "" + array[3];
Given a list
List<String> l = new ArrayList<String>();
l.add("one");
l.add("two");
l.add("three");
I have a method
String join(List<String> messages) {
if (messages.isEmpty()) return "";
if (messages.size() == 1) return messages.get(0);
String message = "";
message = StringUtils.join(messages.subList(0, messages.size() -2), ", ");
message = message + (messages.size() > 2 ? ", " : "") + StringUtils.join(messages.subList(messages.size() -2, messages.size()), ", and ");
return message;
}
which, for l, produces "one, two, and three".
My question is, is there a standard (apache-commons) method that does the same?, eg
WhatEverUtils.join(l, ", ", ", and ");
To clarify. My problem is not getting this method to work. It works just as I want it to, it's tested and all is well. My problem is that I could not find some apache-commons-like module which implements such functionality. Which surprises me, since I cannot be the first one to need this.
But then maybe everyone else has just done
StringUtils.join(l, ", ").replaceAll(lastCommaRegex, ", and");
In Java 8 you can use String.join() like following:
Collection<String> elements = ....;
String result = String.join(", ", elements);
What about join from:
org.apache.commons.lang.StringUtils
Example:
StringUtils.join(new String[] { "one", "two", "three" }, ", "); // one, two, three
To have "and" or ", and" you can simple replace the last comma.
With Java 8, you can use streams with joiners.
Collection<String> strings;
...
String commaDelimited = strings.stream().collect(Collectors.joining(","));
// use strings.parallelStream() instead, if you think
// there are gains to be had by doing fork/join
I like using Guava for this purpose. Neat and very useful:
Joiner.on(",").join(myList)
This kind of code has been written time and time again and you should rather be freed implementing your specific implementation logic.
If you use maven, herewith the dependency:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
It has a bunch of other wonderful cool features too!
This will produce the string "one, two, and three".
List<String> originalList = Arrays.asList("one", "two", "three");
Joiner.on(", ")
.join(originalList.subList(0, originalList.size() - 1))
.concat(", and ")
.concat(originalList.get(originalList.size() - 1));
To produce grammatical output in English there are 3 cases to consider when concatenating a list of strings:
"A"
"A and B"
"A, B, and C.
This can be accomplished using standard Java or Guava like below. The solutions are basically the same and just up to preference what you want to use.
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class JoinListTest {
#Test
public void test_join() {
// create cases (don't need to use ImmutableList builder from guava)
final List<String> case1 = new ImmutableList.Builder<String>().add("A").build();
final List<String> case2 = new ImmutableList.Builder<String>().add("A", "B").build();
final List<String> case3 = new ImmutableList.Builder<String>().add("A", "B", "C").build();
// test with standard java
assertEquals("A", joinListGrammaticallyWithJava(case1));
assertEquals("A and B", joinListGrammaticallyWithJava(case2));
assertEquals("A, B, and C", joinListGrammaticallyWithJava(case3));
// test with guava
assertEquals("A", joinListGrammaticallyWithGuava(case1));
assertEquals("A and B", joinListGrammaticallyWithGuava(case2));
assertEquals("A, B, and C", joinListGrammaticallyWithGuava(case3));
}
private String joinListGrammaticallyWithJava(final List<String> list) {
return list.size() > 1
? String.join(", ", list.subList(0, list.size() - 1))
.concat(String.format("%s and ", list.size() > 2 ? "," : ""))
.concat(list.get(list.size() - 1))
: list.get(0);
}
private String joinListGrammaticallyWithGuava(final List<String> list) {
return list.size() > 1
? Joiner.on(", ").join(list.subList(0, list.size() - 1))
.concat(String.format("%s and ", list.size() > 2 ? "," : ""))
.concat(list.get(list.size() - 1))
: list.get(0);
}
}
Other answers talk about "replacing the last comma", which isn't safe in case the last term itself contains a comma.
Rather than use a library, you can just use one (albeit long) line of JDK code:
public static String join(List<String> msgs) {
return msgs == null || msgs.size() == 0 ? "" : msgs.size() == 1 ? msgs.get(0) : msgs.subList(0, msgs.size() - 1).toString().replaceAll("^.|.$", "") + " and " + msgs.get(msgs.size() - 1);
}
See a live demo of this code handling all edge cases.
FYI, here's a more readable two-liner:
public static String join(List<String> msgs) {
int size = msgs == null ? 0 : msgs.size();
return size == 0 ? "" : size == 1 ? msgs.get(0) : msgs.subList(0, --size).toString().replaceAll("^.|.$", "") + " and " + msgs.get(size);
}
I don't know any Apache String joiner that can support adding and in the joined String.
Here's an untested code that will do what you asked:
public static String join(String separator, List<String> mList, boolean includeAndInText) {
StringBuilder sb = new StringBuilder();
int count = 0;
for (String m: mList) {
if (includeAndInText && (count + 1 != mList.size())) {
sb.append (" and ");
}
sb.append(m);
count++;
if (count < mList.size()) {
sp.append(separator);
}
}
return sb.toString();
}
If you want a more comprehensive solution, there is a brilliant NLG library for that - SimpleNLG
//initialize
NLGFactory nlgFactory = new NLGFactory(Lexicon.getDefaultLexicon());
Realiser realiser = new Realiser(lexicon);
CoordinatedPhraseElement cp = nlgFactory.createCoordinatedPhrase();
cp.setConjunction("and");
//code begins here
List<String> l = new ArrayList<String>();
l.add("one");
l.add("two");
l.add("three");
l.forEach(cp::addCoordinate);
//output
String output = realiser.realise(cp).toString();
This can support any number of array elements without needing to do ugly hacks like "remove last comma".
Improved version from Bohemian♦'s answer. You can choose to remove the nulled items check on personal preferences.
/** Auto Concat Wrapper
* Wraps a list of string with comma and concat the last element with "and" string.
* E.g: List["A", "B", "C", "D"] -> Output: "A, B, C and D"
* #param elements
*/
public static String join(List<String> elements){
if(elements==null){return "";}
List<String> tmp = new ArrayList<>(elements);
tmp.removeAll(Collections.singleton(null)); //Remove all nulled items
int size = tmp.size();
return size == 0 ? "" : size == 1 ? tmp.get(0) : String.join(", ", tmp.subList(0, --size)).concat(" and ").concat(tmp.get(size));
}
Test results:
List<String> w = Arrays.asList("A");
List<String> x = Arrays.asList("A", "B");
List<String> y = Arrays.asList("A", "B", null, "C");
List<String> z = Arrays.asList("A", "B", "C", "D");
System.out.println(join(w));//A
System.out.println(join(x));//A and B
System.out.println(join(y));//A, B and C
System.out.println(join(z));//A, B, C and D
In this way we can join
List<Long> ids = new ArrayList<>();
String idsAsString = String.join(",", ids);
System.out.println(idsAsString);
I have two String lists (a and b) that I wanna join with a comma after each element. I want the elements of list a to be first. I'm also stuck on Java 7
I tried the following but it doesn't work:
StringUtils.join(a, ", ").join(b, ", ");
This works :
ArrayList<String> aAndB = new ArrayList<>();
aAndB.addAll(a);
aAndB.addAll(b);
StringUtils.join(aAndB, ", ");
Is there a shorter way of doing this?
You do not need StringUtils By default List toString() displays elements in comma separated format.
System.out.println (new StringBuilder (aAndB.toString())
.deleteCharAt (aAndB.toString().length ()-1)
.deleteCharAt (0).toString ());
The only thing you need to do is delete square brackets
You can use the guava library like so:
String [] a = {"a", "b", "c"};
String [] b = {"d", "e"};
//using Guava library
String [] joined = ObjectArrays.concat(a, b, String.class);
System.out.println("Joined array : " + Arrays.toString(joined));
// Output: "Joined array : [a, b, c, d, e]"
To get short code you could :
String res = String.join(",", a) + "," + String.join(",", b);
Since you are using Java 7, you could write a static method to perform the task.
List<String> a = Arrays.asList("a", "b", "c");
List<String> b = Arrays.asList("d", "e", "f");
String s = join(",", a, b);
System.out.println(s);
List<Integer> aa = Arrays.asList(101, 102, 103);
List<Integer> bb = Arrays.asList(104, 105, 106);
String ss = join(":", aa, bb);
System.out.println(ss);
}
public static <T> String join(String delimiter, List<T>... lists) {
StringBuilder sb = new StringBuilder();
for (List<T> list : lists) {
for (T item : list) {
sb.append(delimiter);
sb.append(item);
}
}
return sb.substring(delimiter.length()).toString();
}
}
This prints.
a,b,c,d,e,f
101:102:103:104:105:106
I want the Java code for converting an array of strings into an string.
Java 8+
Use String.join():
String str = String.join(",", arr);
Note that arr can also be any Iterable (such as a list), not just an array.
If you have a Stream, you can use the joining collector:
Stream.of("a", "b", "c")
.collect(Collectors.joining(","))
Legacy (Java 7 and earlier)
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
Alternatively, if you just want a "debug-style" dump of an array:
String str = Arrays.toString(arr);
Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer.
Android
Use TextUtils.join():
String str = TextUtils.join(",", arr);
General notes
You can modify all the above examples depending on what characters, if any, you want in between strings.
DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.
Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:
String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);
Produces:
a-b-1
I like using Google's Guava Joiner for this, e.g.:
Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");
would produce the same String as:
new String("Harry, Ron, Hermione");
ETA: Java 8 has similar support now:
String.join(", ", "Harry", "Ron", "Hermione");
Can't see support for skipping null values, but that's easily worked around.
From Java 8, the simplest way I think is:
String[] array = { "cat", "mouse" };
String delimiter = "";
String result = String.join(delimiter, array);
This way you can choose an arbitrary delimiter.
You could do this, given an array a of primitive type:
StringBuffer result = new StringBuffer();
for (int i = 0; i < a.length; i++) {
result.append( a[i] );
//result.append( optional separator );
}
String mynewstring = result.toString();
Try the Arrays.deepToString method.
Returns a string representation of the "deep contents" of the specified
array. If the array contains other arrays as elements, the string
representation contains their contents and so on. This method is
designed for converting multidimensional arrays to strings
Try the Arrays.toString overloaded methods.
Or else, try this below generic implementation:
public static void main(String... args) throws Exception {
String[] array = {"ABC", "XYZ", "PQR"};
System.out.println(new Test().join(array, ", "));
}
public <T> String join(T[] array, String cement) {
StringBuilder builder = new StringBuilder();
if(array == null || array.length == 0) {
return null;
}
for (T t : array) {
builder.append(t).append(cement);
}
builder.delete(builder.length() - cement.length(), builder.length());
return builder.toString();
}
public class ArrayToString
{
public static void main(String[] args)
{
String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};
String newString = Arrays.toString(strArray);
newString = newString.substring(1, newString.length()-1);
System.out.println("New New String: " + newString);
}
}
You want code which produce string from arrayList,
Iterate through all elements in list and add it to your String result
you can do this in 2 ways: using String as result or StringBuffer/StringBuilder.
Example:
String result = "";
for (String s : list) {
result += s;
}
...but this isn't good practice because of performance reason. Better is using StringBuffer (threads safe) or StringBuilder which are more appropriate to adding Strings
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';
String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s
result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s
result = String.join("", strings);
//Java 8 .join: 3ms
Public String join(String delimiter, String[] s)
{
int ls = s.length;
switch (ls)
{
case 0: return "";
case 1: return s[0];
case 2: return s[0].concat(delimiter).concat(s[1]);
default:
int l1 = ls / 2;
String[] s1 = Arrays.copyOfRange(s, 0, l1);
String[] s2 = Arrays.copyOfRange(s, l1, ls);
return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
}
}
result = join("", strings);
// Divide&Conquer join: 7ms
If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.
String array[]={"one","two"};
String s="";
for(int i=0;i<array.length;i++)
{
s=s+array[i];
}
System.out.print(s);
Use Apache Commons' StringUtils library's join method.
String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");
When we use stream we do have more flexibility, like
map --> convert any array object to toString
filter --> remove when it is empty
join --> Adding joining character
//Deduplicate the comma character in the input string
String[] splits = input.split("\\s*,\\s*");
return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors.joining(", "));
If you know how much elements the array has, a simple way is doing this:
String appendedString = "" + array[0] + "" + array[1] + "" + array[2] + "" + array[3];
I am brand new to Java :)
I have 2 String lists and I was wondering what would be the most efficient way to compare the two and have a resulting array which contains strings that are not in the other. For example, I have a list called oldStrings and one called Strings. I have seen the Comparator function but don't fully understand how it works, right now I was thinking I could create a for loop, loop through each string and then save that string:
for (final String str : oldStrings) {
if(!strings.contains(str))
{
getLogger().info(str + " is not in strings list ");
}
}
There's going to be up to 200 strings in this list. Would this be the best way to go about this? Thank you!
Collection firstList = new ArrayList() {{
add("str1");
add("str2");
}};
Collection secondList = new ArrayList() {{
add("str1");
add("str3");
add("str4");
}};
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);
// Here is main part
secondList.removeAll(firstList);
System.out.println("Result: " + secondList);
Update:
More sophisticated version of code
Collection<String> firstList = new ArrayList<String>();
firstList.add("str1");
firstList.add("str2");
Collection<String> secondList = new ArrayList<String>();
secondList.add("str1");
secondList.add("str2");
secondList.add("str3");
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);
// Here is main part
secondList.removeAll(firstList);
Update:
To Get acctual difference between both String list go for this.
Set<String> setOne = new HashSet<String>();
Set<String> setTwo = new HashSet<String>();
setOne.add("1");
setOne.add("2");
setOne.add("5");
setTwo.add("1");
setTwo.add("3");
setTwo.add("4");
Set<String> setTwoDummy = new HashSet<String>(setTwo);
setTwo.retainAll(setOne);
setTwoDummy.addAll(setOne);
setTwoDummy.removeAll(setTwo);
System.out.println(""+setTwoDummy);
First, the problem with your solution is that it will only find elements that are in oldStrings and not strings. If you're going with this approach then you need to loop on the other list as well.
If this is not for homework then check out CollectionUtils.disjunction from Apache Commons Collections.
Compare two lists of strings and have a
resulting array which contains strings
that are not in the other.
The description is ambiguous because we don't we don't know if we need just non matching strings from the first list, the second list, or both. Below is pseudo code for both.
for (String str : oldStrings)
{
if(strings.contains(str))
{
intersectionList.add(str);
}
}
oldStrings.removeAll(intersectionList);
strings.removeAll(intersectionList);
result = strings.addAll(oldStrings).toArray();
Or
copyStrings = strings.clone();
strings.removeAll(oldStrings);
oldStrings.removeAll(copyStrings);
result = strings.addAll(oldStrings).toArray();
You should be using Google Guava's Sets utilities.
Set<String> s = Sets.newHashSet("a", "b", "c", "d");
Set<String> t = Sets.newHashSet("f", "g", "a", "c");
Sets.SetView<String> difference = Sets.difference(s, t);
System.out.println(difference); // prints [b, d]