In my software, since there is no Array data type in SQLite, I saved my ArrayList as a String. Now I need to use my array and want to convert it back to an ArrayList. How can I do it?
Here an example :
ArrayList<String> list = new ArrayList<String>();
list.add("name1");
list.add("name2");
list.add("name3");
list.add("name4");
list.add("name5");
list.add("name6");
String newList = list.toString();
System.out.println(newList);
Result: [name1, name2, name3, name4, name5, name6]
So now how can I convert this into an ArrayList<String>?
I believe this should work :
Arrays.asList(newList.substring(1, newList.length() - 1).replaceAll("\\s", "").split(","));
Take the string, remove the first and last bracket.
Remove each spaces.
Split by comma as delimiter, collect as list.
Note that if really you have to do this for a project, then there is something wrong in your code design. However, if this is just for curiosity purpose then this solution would work.
After testing
ArrayList<String> list = new ArrayList<String>();
list.add("name1");
list.add("name2");
list.add("name3");
list.add("name4");
list.add("name5");
list.add("name6");
String newList = list.toString();
List<String> myList = Arrays.asList(newList.substring(1, newList.length() - 1).replaceAll("\\s", "").split(","));
System.out.println(myList);
would compile properly and print :
[name1, name2, name3, name4, name5, name6]
Edit
As per your comments, if really you want your variable to be an ArrayList<String> instance then you could pass the list to ArrayList constructor :
ArrayList<String> myList = new ArrayList(Arrays.asList(newList.substring(1, newList.length() - 1).replaceAll("\\s", "").split(",")));
You can't cast directly as Arrays.asList use it own builtin java.util.Arrays$ArrayList class.
This is not possible to do without ambiguity. Consider:
ArrayList<String> list = new ArrayList<String>();
list.add("name1, name2");
list.add("name3, name4");
list.add("name5");
list.add("name6");
String newList = list.toString();
System.out.println(newList);
Result: [name1, name2, name3, name4, name5, name6]
In order to accurately recover the original elements in the general case, your string format must be smarter than ArrayList.toString(). Consider a pre-defined way of encoding lists of strings, perhaps a JSON array, which would result in something like this for my example:
["name1, name2", "name3, name4", "name5", "name6"]
JSON also defines how to handle strings with quotes via escaping and/or use of alternate string start/end characters ' and ":
["he said, 'hello'", 'she said, "goodbye"', 'I said, "it\'s raining"']
(I also agree with other commenters that your database design should be reconsidered, but wanted to provide a clear answer illustrating the issues with string encodings of lists.)
Then it the method that only accepts strings would be able to add a case where something like this were passed in?
methodThatOnlyAllowsStrings((Object)list);
Related
I have elements that is declared in a list variable such as:
List<List<String>> textList = new ArrayList<>();
The elements are added such as:
textList.add(Arrays.asList(p)); //adding elements
The only way I could output the elements inside the variable is by using:
for(List<String> s: textList){
System.out.println(s); }
which output elements like this:
[He is a boy.]
[He likes apple.]
[She is a girl.]
Now, I would like to store them in an array so that the elements will look like this when outputted.
[He is a boy., He likes apple., She is a girl.]
I've tried
String[] textArr = new String[textList.size()];
textArr = textList.toArray(textArr);
for(String s : textArr){
System.out.println(s);}
but I got an error about:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)
So, how do I convert the elements inside a list into array using the proper way. Thanks!
Your problem is that you are not storing Strings in your list textList.
textList.add(Arrays.asList(p));
As the type says, you have a List of List of String here.
So you can't take the elements of that list and assume they are Strings. Because they aren't! The error message tells you that: toArray() wants strings it can put into that array of strings, but you give it a List of List of String!
But thing is: what you are describing here doesn't make sense in the first place. Printing strings shouldn't care if strings are in an array or a List.
What I mean is: when you manually iterate a List or an array to print its content, then it absolutely doesn't matter if you iterate a List or an array. The code is even the same:
for (String someString : someCollection) {
System.out.println(someString);
}
someCollection can be both: array or List!
In other words: the idea to turn data that is nicely stored within Lists into arrays for printing simply doesn't make any sense. To the contrary: you are probably calling toString() on your List object, and the result of that ... isn't 100% what you want. But I guarantee you: calling toString() on some array will result in something you totally will not want.
Long story short: forget about converting to Arrays; simply iterate your List of List of Strings and use a StringBuilder to collect the content of that collection the way you want to see it (you simply append those [ ] chars to that builder in those places you want them to see).
(if you insist on that conversion to array, the key point there to understand is that only a List of String can be turned into an array of string. So a List of List ... doesnt work that easy).
Using streams and flatMap, you can do this:
List<List<String>> list = ...;
String[] strings = list.stream().flatMap(l -> l.stream()).collect(Collectors.toList()).toArray(new String[0]);
This is equivalent to using a loop (You can use two nested for loops as suggested in the comments instead by replacing the addAll, but why?):
List<List<String>> list = ...;
List<String> stringList = new ArrayList<>();
for (List<String> l : list)
stringList.addAll(l);
String[] strings = list.toArray(new String[stringList.size()]);
You can use Iterator in order to go over every element of the list, instance of the for each statement (I personally like the iterators more). The code you could use would be something like
//Your list
List<List<String>> textList = new ArrayList<>();
//The iterators
Iterator<List<String>> itList = textList.iterator();
Iterator<String> itString;
//The string to store the phrases
String s[] = new String[textList.size()];
int i =0;
//First loop, this seeks on every list of lists
while(itList.hasNext()){
//Getting the iterator of strings
itString = itList.next().iterator();
s[i] = "";
//2nd loop, it seeks on every List of string
while(itString.hasNext()){
s[i] = s[i].concat(itString.next());
}
s[i] = s[i].concat(".");
i++;
}
First I have two strings.
String name = "my name is";
String address = "my address is";
Then I want to split the 'name' string value from the space character and add to a list.
List word_list = new ArrayList();
word_list.add(Arrays.asList(name.split(" ")));
Then similarly I want to split the 'address' string value and add to the same 'word_list'.
word_list.add(Arrays.asList(address.split(" ")));
From this finally what I get is,
[[my, name, is], [my, address, is]]
But what I want is,
[my, name, is, my, address, is]
Is there any shorter method other than writing a loop to solve this problem?
You need addAll :
word_list.addAll(Arrays.asList(name.split(" ")));
word_list.addAll(Arrays.asList(address.split(" ")));
add treats the argument as a single element to be added to the list. addAll expects a Collection of elements to be added to the list.
BTW, if you defined your list as List<String> word_list = new ArrayList<String>();, the compiler would have prevented you from calling add with a List as an argument.
There's a function that does what you want:
public String[] mergeArrays(String[] mainArray, String[] addArray) {
String[] finalArray = new String[mainArray.length + addArray.length];
System.arraycopy(mainArray, 0, finalArray, 0, mainArray.length);
System.arraycopy(addArray, 0, finalArray, mainArray.length, addArray.length);
return finalArray;
}
By the way, Apache Commons Lang Lib has a one-line function to do that:
[ArrayUtils.addAll(T\[\], T...)][1]
There are two issues in your code.
Your word_list is not generic. You should declare and initialize it as:
List<String> word_list = new ArrayList<String>();
... or optionally use the diamond syntax from Java 7 on:
List<String> word_list = new ArrayList<>();
This way, you ensure type safety, as in, compile-time checks on what gets in (we want Strings).
Since your List is not generic, it will take any Object. In this case, you are adding a List<String>, not a String
Instead, use word_list.addAll(Arrays.asList(name.split(" ")))
How can I convert this string into a java list (java.util.List) of three elements ?
{Electronic,Pop,Rock}
I already use Google Guava, so that would be a good solution but I cant see one
List<String> result = Splitter.on(CharMatcher.anyOf("{,}"))
.trimResults()
.omitEmptyStrings()
.splitToList();
Relevant documentation: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Splitter.html
Your List will be of type string so --> List< String > or you could use the ArrayList object.
See this question for pointers.
String tunes = "Electronic,Pop,Rock";
String[] splits = tunes.split(",");
List<String> wordList = Arrays.asList(splits);
Create an array as displayed below.
String sourceString = "{Electronic,Pop,Rock}";
// it will remove curly braces
sourceString = sourceString.substring(1,sourceString.length()-1);
String[] arr = sourceString.split(",");
However you can use Array in place of List but if it is really necessary to make list then add following line.
List<String> list = Arrays.asList(arr);
I have a string places="city,city,town". I need to get "city,town". Basically get rid of duplicate entries in the comma separated string.
places.split(","); will give me array of String. I wonder, if I can pass this array to a HashSet or something, which will automatically get rid of duplicates, but trying something like:
HashSet test=new HashSet(a.split(","));
gives the error:
cannot find symbol
symbol : constructor HashSet(java.lang.String[])
Any neat way of achieving this, preferably with least amount of code?
HashSet<String> test=new HashSet<String>(Arrays.asList(s.split(",")));
this is because HashSet does not have a constructor that expects an array. It expects a collection, which is what I am doing here by Arrays.asList(s.split(","))
String s[] = places.split(",");
HashSet<String> hs = new HashSet<String>();
for(String place:s)
hs.add(place);
If you care about the ordering I'd suggest you use a LinkedHashSet.
LinkedHashSet test = new LinkedHashSet(Arrays.asList(a.split(",")));
Another way of doing this in Java 8 would be:
Lets say you have a string str which is having some comma separated values in it. You can convert it into stream and remove duplicates and join back into comma separated values as given below:
String str = "1,2,4,5,3,7,5,3,3,8";
str = String.join(",",Arrays.asList(str.split(",")).stream().distinct().collect(Collectors.toList()));
This will give you a String str without any duplicate
String[] functions= commaSeperatedString.split(",");
List<String> uniqueFunctions = new ArrayList<>();
for (String function : functions) {
if ( !uniqueFunctions.contains(function.trim())) {
uniqueFunctions.add(function.trim());
}
}
return String.join(",",uniqueFunctions);
or you can use linkedHashset
LinkedHashSet result = new LinkedHashSet(Arrays.asList(functions.split(",")));
I have got into a strange strange situation. I have 3 sets of strings like this
String set1q1="something"; //associated with randomNum=1
String set1q2="something";
String set1q3="something";
String set1q4="something";
... and so on
String set2q1="something"; //randomNum=2
String set2q2="something";
String set2q3="something";
String set2q4="something";
... and so on
String set3q1="something"; //randomNum=3
String set3q2="something";
String set3q3="something";
String set3q4="something";
... and so on
All these strings are initialised only once. Now in my program i generate a random number between 1-3. I converted this random number into a string and stored it into a string called set.
String set=randomNum.toString();
Now next intead of using "if-else" to send the data(if randomnum=1 send set1q1-5, if randomnum=2 then send set2q1-5), I want the appropriate data to be sent using one line.
For example: if random no 2 is chosen then set2q1 has to be sent where the "2" in between is has to be the value of "set"(which is defined above).
set"set"q1 //where set can be 1,2,3
Is there any way to do this?
What you are asking for is not possible;1 it's just not the way Java works. Why don't you just use an array, or a collection?
List<List<String>> allTheStrings = new ArrayList<List<String>>();
List<String> myStrings = null;
// Add a subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
// Add another subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
...
// Obtain one of the strings
String str = allTheStrings.get(1).get(2);
1. Except in the case where these variables are members of a class, in which case you could use reflection. But really, don't.
It is not possible. Local variable identifiers are converted to numbers (stack offsets) during compilation. But you should use arrays or collections anyway
Sounds like you want to index Strings by two indices. You should use a two-dimensional String array: String[][] strings. You may then access the desired string with strings[n][m]
Or you can achieve the same effect with a List<List<String>> strings if you need the dimensions of your 2D array to grow dynamically. You'd access the value you need with strings.get(n).get(m)
If you really want to access your strings by a composed name such as set2q1, then you just need a Map<String, String> strings. Then you'd access each value with strings.get("set" + m + "q" + n)
looks to me you should look into arrays, like this:
String[] strings = new String[]{"xxx", "yyy", "zzz"};
String string = strings[randomNumber];
create an arraylist instead and reference using the list index