ArrayList of Strings to one single string - java

I have an array list of strings (each individual element in the array list is just a word with no white space) and I want to take each element and append each next word to the end of a string.
So say the array list has
element 0 = "hello"
element 1 = "world,"
element 2 = "how"
element 3 = "are"
element 4 = "you?"
I want to make a string called sentence that contains "hello world, how are you?"

As of Java 8, this has been added to the standard Java API:
String.join() methods:
String joined = String.join("/", "2014", "10", "28" ); // "2014/10/28"
List<String> list = Arrays.asList("foo", "bar", "baz");
joined = String.join(";", list); // "foo;bar;baz"
StringJoiner is also added:
StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"
Plus, it's nullsafe, which I appreciate. By this, I mean if StringJoiner encounters a null in a List, it won't throw a NPE:
#Test
public void showNullInStringJoiner() {
StringJoiner joinedErrors = new StringJoiner("|");
List<String> errorList = Arrays.asList("asdf", "bdfs", null, "das");
for (String desc : errorList) {
joinedErrors.add(desc);
}
assertEquals("asdf|bdfs|null|das", joinedErrors.toString());
}

Like suggested in the comments you can do it using StringBuilder:
StringBuilder listString = new StringBuilder();
for (String s : list)
listString.append(s).append(" ");
or without the explicit loop:
list.forEach(s -> listString.append(s).append(" "));
or even more elegant with Java 8 capabilities:
String listString = String.join(" ", list);

Use StringUtils to solve this.
e.g. Apache Commons Lang offers the join method.
StringUtils.join(myList,","))
It will iterate through your array or list of strings and will join them, using the 2nd parameter as seperator. Just remember - there is always a library for everything to make things easy.

Java 8
final String concatString= List.stream()
.collect(Collectors.joining(" "));

Well, a standard for loop should work:
String toPrint = "";
for(int i=0; i<list.size(); i++){
toPrint += list.get(i)+" ";
}
System.out.println(toPrint);
Hope that helps!

Simplest way:
String ret = "";
for (int i = 0; i < array.size(); i++) {
ret += array.get(i) + " ";
}
But if your array is long, performance of string concat is poor. You should use StringBuilder class.

this is simple method
String value = TextUtils.join(" ", sample);
sample is arraylist

Related

how to not insert extra space at the end or beginning of space separated strings

I want to represent a list [1,2,3,4] like "\"1 2 3 4\"". Note the escaped quotes and the lack of a space between them and their neighbouring numbers. How can I achieve this? It's such a trivial thing, but it's tricky since I'm working with a TreeSet, not an array. Is this even possible with a for loop or do I have to resort to using the TreeSet iterator?
public String positionsRep(TreeSet<Integer> positions){
StringBuilder s = new StringBuilder("");
s.append("\"");
for(Integer pos: positions){
posStr = Integer.toString(pos);
s.append(posStr);
s.append(" ");
}
s.append("\"");
return s.toString();
}
Just treat the first number a bit differently:
public String positionsRep(TreeSet<Integer> positions){
StringBuilder s = new StringBuilder("");
s.append("\"");
boolean isFirst = true;
for(Integer pos: positions){
if (!isFirst) {
s.append(" ");
}
posStr = Integer.toString(pos);
s.append(posStr);
isFirst = false;
}
s.append("\"");
return s.toString();
}
However, it might be better to just use a StringJoiner instead of the StringBuilder, it does exactly what you want if initialized with (" ", "\"", "\""). This should look somehow like that:
StringJoiner sj = new StringJoiner(" ", "\"", "\"");
for (Integer i: positions) {
sj.add(i.toString());
}
String result = sj.toString();
Or even shorter using streams:
import java.util.stream.Collectors;
positions.stream().map(Integer::toString).collect(Collectors.joining(" ", "\"", "\""));
You can generate an Array from that TreeSet and the use the string properties to join the elements by a space and then add the special char that you need
Example:
TreeSet<String> playerSet = new TreeSet<String>();
playerSet.add("1");
playerSet.add("2");
playerSet.add("3");
playerSet.add("4");
StringBuilder sr = new StringBuilder();
sr.append("\"").append(String.join(" ", new ArrayList<String> (playerSet))).append("\"");
System.out.println(sr.toString());

Java - Split and trim in one shot

I have a String like this : String attributes = " foo boo, faa baa, fii bii," I want to get a result like this :
String[] result = {"foo boo", "faa baa", "fii bii"};
So my issue is how should to make split and trim in one shot i already split:
String[] result = attributes.split(",");
But the spaces still in the result :
String[] result = {" foo boo", " faa baa", " fii bii"};
^ ^ ^
I know that we can make a loop and make trim for every one but I want to makes it in shot.
Use regular expression \s*,\s* for splitting.
String result[] = attributes.split("\\s*,\\s*");
For Initial and Trailing Whitespaces
The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:
String result[] = attributes.trim().split("\\s*,\\s*");
Using java 8 you can do it like this in one line
String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);
If there is no text between the commas, the following expression will not create empty elements:
String result[] = attributes.trim().split("\\s*,+\\s*,*\\s*");
You can do it with Google Guava library this way :
List<String> results = Splitter.on(",").trimResults().splitToList(attributes);
which I find quite elegant as the code is very explicit in what it does when you read it.
ApaceCommons StringUtils.stripAll function can be used to trim individual elements of an array. It leaves the null as null if some of your array elements are null.
Here,
String[] array = StringUtils.stripAll(attributes.split(","));
create your own custom function
private static String[] split_and_trim_in_one_shot(String string){
String[] result = string.split(",");
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
Overload with a consideration for custom delimiter
private static String[] split_and_trim_in_one_shot(String string, String delimiter){
String[] result = string.split(delimiter);
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
with streams
public static List<String> split(String str){
return Stream.of(str.split(","))
.map(String::trim)
.map (elem -> new String(elem))//optional
.collect(Collectors.toList());
What about spliting with comma and space:
String result[] = attributes.split(",\\s");
// given input
String attributes = " foo boo, faa baa, fii bii,";
// desired output
String[] result = {"foo boo", "faa baa", "fii bii"};
This should work:
String[] s = attributes.trim().split("[,]");
As answered by #Raman Sahasi:
before you split your string, you can trim the trailing and leading spaces. I've used the delimiter , as it was your only delimiter in your string
String result[] = attributes.trim().split("\\s*,[,\\s]*");
previously posted here: https://blog.oio.de/2012/08/23/split-comma-separated-strings-in-java/
Best way is:
value.split(",").map(function(x) {return x.trim()});

Is there simple regex to convert Java String List to Oracle IN condition?

For example:
There is a List of String (ArrayList < String >) shopList, and output toString() like this
[bread, sugar, butter]
now I need to convert this List to an Oracle IN condition, so that it become:
('bread', 'sugar', 'butter')
I use
String shopListString= "(".concat(shopList.toString().replaceAll("[\\s\\[\\]]", "'")).concat(")");
but first, I try to avoid concat but use regex alone, also it just output following which is wrong:
('bread,'sugar,'butter')
only last item comes with beginning '
Here's a Java 8 example:
// example list
List<String> myList = new ArrayList<String>(){
{add("bread");add("sugar");add("butter");}
};
// result
// initializing StringBuilder with starting "("
String oracle = myList
.stream()
// collecting as "," separated CharSequence, enclosed in "(" and ")"
.collect(Collectors.joining("','", "('", "')"));
System.out.println(oracle);
Output
('bread','sugar','butter')
Notes
The idea here is to use (hidden) iteration rather than parsing and transforming the String representation of the List.
In Java idioms older than Java 8 that would require a little more code, and some "imperative"-styled ugliness (see valid answer from Casimir et Hippolyte).
Thanks to Keppil for the much improved solution.
As Andreas mentions, beware unsanitized values. You may want to build a format String with as many placeholders as your List's elements, then use a PreparedStatement instead.
There is a simple way base on #Keppil:
"('"+ StringUtils.join(myList, "','") + "')"
This is origin answer use group variable to replace:
"("+ StringUtils.join(myList, ",").replaceAll("(\\w+)", "'$1'") + ")"
You can use StringUtils join string and surround group variable to replace the word.
loop over your arrayList elements and use a stringBuilder.
StringBuilder sb = new StringBuilder("('");
int lastIndex = myList.size() - 1;
for (int i=0; i < lastIndex; i++) {
sb.append(myList.get(i));
sb.append("','");
}
sb.append(myList.get(lastIndex));
sb.append("')");
Note: I assumed that the arrayList isn't empty.
StringBuffer sb = new StringBuffer("(");
//assume this list is populated
List<String> str = new ArrayList<String>();
for (int i =0;i<str.size();i++) {
String temp = "'" + str.get(i) + "'";
sb.append(temp);
if(i != (str.size() -1)) {
sb.append(",");
}
}
sb.append(")");
System.out.println(sb.toString());

Adding comma separated strings to an ArrayList and vice versa

How to add a comma separated string to an ArrayList? My string "returnedItems" could hold 1 or 20 items which I'd like to add to my ArrayList "selItemArrayList".
After the ArrayList has been populated, I'd like to later iterate through it and format the items into a comma separated string with no spaces between the items.
String returnedItems = "a,b,c";
List<String> sellItems = Arrays.asList(returnedItems.split(","));
Now iterate over the list and append each item to a StringBuilder:
StringBuilder sb = new StringBuilder();
for(String item: sellItems){
if(sb.length() > 0){
sb.append(',');
}
sb.append(item);
}
String result = sb.toString();
One-liners are always popular:
Collections.addAll(arrayList, input.split(","));
split and asList do the trick:
String [] strings = returnedItems.split(",");
List<String> list = Arrays.asList(strings);
Simple one-liner:
selItemArrayList.addAll(Arrays.asList(returnedItems.split("\\s*,\\s*")));
Of course it will be more complex if you have entries with commas in them.
This can help:
for (String s : returnedItems.split(",")) {
selItemArrayList.add(s.trim());
}
//Shorter and sweeter
String [] strings = returnedItems.split(",");
selItemArrayList = Arrays.asList(strings);
//The reverse....
StringBuilder sb = new StringBuilder();
Iterator<String> iter = selItemArrayList.iterator();
while (iter.hasNext()) {
if (sb.length() > 0)
sb.append(",");
sb.append(iter.next());
}
returnedItems = sb.toString();
If the strings themselves can have commas in them, things get more complicated. Rather than rolling your own, consider using one of the many open-source CSV parsers. While they are designed to read in files, at least OpenCSV will also parse an individual string you hand it.
Commons CSV
OpenCSV
Super CSV
OsterMiller CSV
If the individual items aren't quoted then:
QString str = "a,,b,c";
QStringList list1 = str.split(",");
// list1: [ "a", "", "b", "c" ]
If the items are quoted I'd add "[]" characters and use a JSON parser.
You could use the split() method on String to convert the String to an array that you could loop through.
Although you might be able to skip the looping and parsing with a regular expression to remove the spaces using replaceAll() on a String.
String list = "one, two, three, four";
String[] items = list.split("\\p{Punct}");
List<String> aList = Arrays.asList(items);
System.out.println("aList = " + aList);
StringBuilder formatted = new StringBuilder();
for (int i = 0; i < items.length; i++)
{
formatted.append(items[i].trim());
if (i < items.length - 1) formatted.append(',');
}
System.out.println("formatted = " + formatted.toString());
import com.google.common.base.*;
Iterable<String> items = Splitter.on(",").omitEmptyStrings()
.split("Mango,Apple,Guava");
// Join again!
String itemsString = Joiner.join(",").join(items);
String csv = "Apple, Google, Samsung";
step one : converting comma separate String to array of String
String[] elements = csv.split(",");
step two : convert String array to list of String
List<String> fixedLenghtList = Arrays.asList(elements);
step three : copy fixed list to an ArrayList
ArrayList listOfString = new ArrayList(fixedLenghtList);
System.out.println("list from comma separated String : " + listOfString);
System.out.println("size of ArrayList : " + listOfString.size());
Output :
list of comma separated String : [Apple, Google, Samsung]
size of ArrayList : 3

Parsing comma delimited text in Java

If I have an ArrayList that has lines of data that could look like:
bob, jones, 123-333-1111
james, lee, 234-333-2222
How do I delete the extra whitespace and get the same data back? I thought you could maybe spit the string by "," and then use trim(), but I didn't know what the syntax of that would be or how to implement that, assuming that is an ok way to do it because I'd want to put each field in an array. So in this case have a [2][3] array, and then put it back in the ArrayList after removing the whitespace. But that seems like a funny way to do it, and not scaleable if my list changed, like having an email on the end. Any thoughts? Thanks.
Edit:
Dumber question, so I'm still not sure how I can process the data, because I can't do this right:
for (String s : myList) {
String st[] = s.split(",\\s*");
}
since st[] will lose scope after the foreach loop. And if I declare String st[] beforehand, I wouldn't know how big to create my array right? Thanks.
You could just scan through the entire string and build a new string, skipping any whitespace that occurs after a comma. This would be more efficient than splitting and rejoining. Something like this should work:
String str = /* your original string from the array */;
StringBuilder sb = new StringBuilder();
boolean skip = true;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (skip && Character.isWhitespace(ch))
continue;
sb.append(ch);
if (ch == ',')
skip = true;
else
skip = false;
}
String result = sb.toString();
If you use a regex for you split, you can specify, a comma followed by optional whitespace (which includes spaces and tabs just in case).
String[] fields = mystring.split(",\\s*");
Depending on whether you want to parse each line separately or not you may first want to create an array split on a line return
String[] lines = mystring.split("\\n");
Just split() on each line with the delimiter set as ',' to get an array of Strings with the extra whitespace, and then use the trim() method on the elements of the String array, perhaps as they are being used or in advance. Remember that the trim() method gives you back a new string object (a String object is immutable).
If I understood your problem, here is a solution:
ArrayList<String> tmp = new ArrayList<String>();
tmp.add("bob, jones, 123-333-1111");
tmp.add(" james, lee, 234-333-2222");
ArrayList<String> fixedStrings = new ArrayList<String>();
for (String i : tmp) {
System.out.println(i);
String[] data = i.split(",");
String result = "";
for (int j = 0; j < data.length - 1; ++j) {
result += data[j].trim() + ", ";
}
result += data[data.length - 1].trim();
fixedStrings.add(result);
}
System.out.println(fixedStrings.get(0));
System.out.println(fixedStrings.get(1));
I guess it could be fixed not to create a second ArrayLis. But it's scalable, so if you get lines in the future like: "bob, jones , bobjones#gmail.com , 123-333-1111 " it will still work.
I've had a lot of success using this library.
Could be a bit more elegant, but it works...
ArrayList<String> strings = new ArrayList<String>();
strings.add("bob, jones, 123-333-1111");
strings.add("james, lee, 234-333-2222");
for(int i = 0; i < strings.size(); i++) {
StringBuilder builder = new StringBuilder();
for(String str: strings.get(i).split(",\\s*")) {
builder.append(str).append(" ");
}
strings.set(i, builder.toString().trim());
}
System.out.println("strings = " + strings);
I would look into:
http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)
or
http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/java/util/Scanner.html
you can use Sting.split() method in java or u can use split() method from google guava library's Splitter class as shown below
static final Splitter MY_SPLITTER = Splitter.on(',')
.trimResults()
.omitEmptyStrings();

Categories

Resources