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
Related
I have some large files with comma separated data in them. Something like:
firstname,middlename,lastname
James,Tiberius,Kirk
Mister,,Spock
Leonard,,McCoy
I'm using a StringTokenizer to parse the data:
StringTokenizer st = new StringTokenizer(sLine, ",");
while (st.hasMoreTokens()) {
String sTok = st.nextTokens;
tokens.add(tok);
}
The problem is, on lines with no middle name, I only get two tokens, { "Mister", "Spock" }, but I want three tokens, { "Mister, "", "Spock" }
QUESTION: How do I get empty tokens included when parsing my comma separated data?
Thanks!
You can use the String#split(String regex) method.
String[] split = sLine.split(",");
for (String s : split) {
System.out.println("S = " + s); //Note there will be one empty S
tokens.add(s);
}
Use split(",") instead of a StringTokenizer:
String[] aux = sLine.split(",");
for(int i = 0; i < aux.length; i++) {
String sTok = aux[i];
tokens.add(sTok);
}
You can see in the documentation that StringTokenizer is a legacy class and is only kept for retro-compatibility:
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
Use split method, but pass -1 as the second argument to keep empty strings
sLine.split(",", -1);
Consider the use of Splitter of Guava Splitter
And you can create an splitter with or without omit empty Strings.
//Example without omit empty Strings (default)
Splitter splitterByComma = Splitter.on(",");
Iterable<String> split = splitterByComma.split("Mister,,Spock");
//Example omitting empty Strings
Splitter splitterByComma = Splitter.on(",").omitEmptyStrings();
Iterable<String> split = splitterByComma.split("Mister,,Spock");
This question already has answers here:
How to separate specific elements in string java
(3 answers)
Closed 9 years ago.
so the method takes two parameters, first is the String you will be splitting, second is the delimiter(where to split at).
So if I pass in "abc|def" as the first parameter and "|" as the second I should get a List that returns "abc, def" the problem I'm having is that my if statement requires the delimiter is in the current string to be accessed. I can't think of a better condition, any help?
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
for(int i=0;i<string.length();i++){
newString += string.charAt(i);
if(newString.contains(delimiter)){
//list.remove(string);
list.add(newString.replace(delimiter, ""));
newString="";
}
}
return list;
}
Badshaah and cmvaxter code for split using builtin function split(regex) won't work. as you pass "|" as a delimiter "sam|ple" it wont be splitted as [sam,ple] because ( | , + , * , ...) are all used in regex for other purposes.
and u can check character by character, if the delimiter is a character
loop(each char)
if(not delim)
append to list[i]
else
increment i, discard char
learning purpose it might be needed in c or c++ (even they 've strtok to split strings) to improve effeciency or to modify something differently. [may split differently not using regex]
Its best to use existing system libraries and functions.
if u want to use your function do something like
write these functions yourself
findpos(delim) // gives position of delimiter found in string
substring(pos,len) //len:size of delimiter
getlist(String str,String delim)
//for each delim found use substring and append to list
use some pattern matching algorithms like KMP or something u know.
Change your whole method to.
public List<String> splitIt(String string, String delimiter){
String[] out = string.split(delimiter);
return Arrays.asList(out);
}
Since you are iterating through the string, your if should be based on the character you are inspecting, instead of invoking contains each time:
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
int lastDelimiter = 0;
for (int i=0; i<string.length(); i++) {
if (delimiter.equals("" + string.charAt(i))) {
list.add(string.substring(lastDelimiter, i));
lastDelimiter = i + 1;
}
}
if (lastDelimiter != string.length())
list.add(string.substring(lastDelimiter, string.length()));
return list;
}
For the sake of learning, I think your original attempt lends itself to a recursive solution. The general idea in this case would be:
If there are no delimiters in the string and it is not empty, return the string as the only element in a new list
Otherwise
find the first occurrence of the delimiter
extract the string from the beginning up to the delimiter, call it 'found'
remove the delimiter
recursively call this method, passing it the remainder of the string and the delimiter
append 'found' to the list returned from #4, and return that list
The String class already supports a split method that I believe does exactly what you are looking to do.
String[] s = "abc|def".split("\\|");
List<String> list = Arrays.asList(s);
If you want to do it yourself, the code might look something like this:
char delim = "|".charAt(0);
String s = "abc|def|ghi";
char[] chars = s.toCharArray();
StringBuilder sb = new StringBuilder();
List<String> list = new ArrayList<String>();
for(char c: chars){
if (c == delim){
list.add(sb.toString());
sb = new StringBuilder();
}
else{
sb.append(c);
}
}
if (sb.length() > 0) list.add(sb.toString());
System.out.println(list);
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
I am stuck splitting a string into pieces to store the pieces into an ArrayList. I can split the string onto " ", but I'd like to split the string onto "farmersmarket" and store it into an Arraylist. To be able to return one of the indexed pieces of string.
ArrayList<String> indexes = new ArrayList<String>();
String s = file;
for(String substring: s.split(" ")){
indexes.add(substring);
}
System.out.println(indexes.get(2));
Any ideas to split a string on "farmersmarket"?
String[] tokens = yourString.split("farmersmarket");
And afterwards you don't need an Arraylist to get a specific element of the tokens. You can access every token like this
String firstToken = tokens[0];
String secondToken = tokens[1];
If you need a List you can do
List<String> list = Arrays.asList(tokens);
and if it has to be an Arraylist do
ArrayList<String> list = new ArrayList<String>(Arrays.asList(tokens));
Assuming that you still want to return a list of strings when the input string doesn't have the character on which you are splitting, Arrays.asList(inputString.split(" ")) should work.
E.g. Arrays.asList("farmersmarket".split(" ")) would return a list that contains only one element--farmersmarket.
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();