adding elements in a list to another list - java

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(" ")))

Related

Restore List from a String in Java [duplicate]

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);

Converting List<List<String>> to array

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++;
}

Add multiple numbered objects to ArrayList

Suppose I have a lot of String Variables(100 for example):
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
....
String str100 = "zzz";
I want to add these String variables to ArrayList, what I am doing now is
ArrayList<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
...
list.add(str100);
I am curious, is there a way to use a loop? For example.
for(int i = 1; i <= 100; i++){
list.add(str+i)//something like this?
}
Use an array:
String[] strs = { "abc","123","zzz" };
for(int i = 0; i < strs.length; i++){
list.add(strs[i]); //something like this?
}
This idea is so popular that there's built-in methods to do it. For example:
list.addAll( Arrays.asList(strs) );
will add your array elements to an existing list. Also the Collections class (note the s at the end) has static methods that work for all Collection classes and do not require calling Arrays.asList(). For example:
Collections.addAll( list, strs );
Collections.addAll( list, "Larry", "Moe", "Curly" );
If you just want a list with only the array elements, you can do it on one line:
List<String> list = Arrays.asList( strs );
Edit: Many other classes in the Java API support this addAll() method. It's part of the Collection interface. Other classes like Stack, List, Deque, Queue, Set, and so forth implement Collection and therefore the addAll() method. (Yes some of those are interfaces but they still implement Collection.)
If you are using Java 9 then easily you can add the multiple String Objects into Array List Like
List<String> strings = List.of("abc","123","zzz");
If you want to stick to good practice, declare your Strings in an array:
String[] strs = new String[]{ "abc", "123", "aaa", ... };
for (String s : strs) // Goes through all entries of strs in ascending index order (foreach over array)
list.add(s);
If strX would be class fields then you could try using reflection - link to example of accessing fields and methods.
If it is local variable then you can't get access to its name so you will not be able to do it (unless str would be array, so you could access its values via str[i] but then you probably wouldn't need ArrayList).
Update:
After you updated question and showed that you have 100 variables
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
//...
String str100 = "zzz";
I must say that you need array. Arrays ware introduced to programming languages precisely to avoid situation you are in now. So instead of declaring 100 separate variables you should use
String[] str = {"abc", "123", "aaa", ... , "zzz"};
and then access values via str[index] where index is value between 0 and size of your array -1, which in you case would be range 0 - 99.
If you would still would need to put all array elements to list you could use
List<String> elements = new ArrayList<>(Arrays.asList(str));
which would first
Arrays.asList(str)
create list backed up by str array (this means that if you do any changes to array it will be reflected in list, and vice-versa, changes done to list from this method would affect str array).
To avoid making list dependant on state of array we can create separate list which would copy elements from earlier list to its own array. We can simply do it by using constructor
new ArrayList<>(Arrays.asList(str));
or we can separate these steps more with
List<String> elements = new ArrayList<>();//empty list
elements.addAll(Arrays.asList(str));//copy all elements from one list to another
Yes. The way to use a loop is not to declare 100 string variables. Use one array instead.
String[] str = new String[101];
str[1] = "abc";
str[2] = "123";
str[3] = "aaa";
....
str[100] = "zzz";
(I made the indexes go from 1 to 100 to show how it corresponds to your original code, but it's more normal to go from 0 to 99 instead, and to initialize it with an array initializer as in #markspace's answer.)
The following creates the ArrayList on the specific String values you have:
ArrayList<String> list1 = new ArrayList<String>() {{addAll(Arrays.asList(new String[]{"99", "bb", "zz"}));}};
Or, if it's just some distinct values you want, use this for say - 10 of them:
ArrayList<String> list2 = new ArrayList<String>() {{for (int i=0; i<10; i++) add(""+System.currentTimeMillis());}};

How can I conver this string into a java list?

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);

Referring a variable with a variable in java

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

Categories

Resources