Add String Arrays in ArrayList - java

I have an ArrayList defined as:
ArrayList<String[]> params=new ArrayList<String[]>();
It contains parameters ("name", value) in String Arrays. I would like to insert elements in the ArrayList:
params.add({"param1", param1});
But when I try that I get an error.
What is the simplest way to add String Arrays in ArrayList. Do I have to declare a new array each time?

A declaration is the only time you can just use braces, e.g.
String[] test = {"param1", param1};
In all other times, you must use new String[] also.
params.add(new String[] {"param1", param1});

Make a string with some special sequence. Add it in ArrayList and then split it when you need it. For example:
ArrayList<String> str_list = new ArrayList<String>();
String str = "name&&&value";
// Add str to str_list
str_list.add(str);
Then fetch it from arraylist and split it using following code:
String str1 = str_list.get(index);
String[] values = str1.split("&&&");
values[0] will be name and values[1] will be value.

You should read up on ArrayLists here
But after initialization you can do this:
params.add("String");
params.add(aStringObject);
Your initialization is incorrect as well; If you want a ArrayList of Strings it should be:
ArrayList<String> params = new ArrayList<String>();

Related

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

Java- Add each word to an arraylist?

this may be pretty simple, but for some reason I am blanking right now.
Suppose I had a string "Hello I Like Sports"
How would I add each word to an arraylist (so each word is in an index in the arraylist)?
Thanks in advance!
ArrayList<String> wordArrayList = new ArrayList<String>();
for(String word : "Hello I like Sports".split(" ")) {
wordArrayList.add(word);
}
The first thing to do is to split that sentence up into pieces. The way to do that is to use String.split That will return an Array of Strings.
Since you want it in an ArrayList, the next thing you have to do is loop through every String in the array and add it to an ArrayList
String[] words = sentence.split(" ");
list.addAll(Arrays.asList(words));
Try this:
public static void main(String[] args) {
String stri="Hello I Like Sports";
String strar[]=stri.split(" ");
ArrayList<String> arr = new ArrayList<String>(Arrays.asList(strar));
for(int x=0;x<arr.size();x++){
System.out.println("Data :"+arr.get(x));
}
}
Output :
Data :Hello
Data :I
Data :Like
Data :Sports
you can use the split method of the String and split on spaces to get each word in a String array. You can then use that array to create an arrayList
String sentence ="Hello I Like Sports";
String [] words = sentence.split(" ");
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(words));
String.split()
Arrays.asList()
A little search would have done the work.
Still I am giving a solution to this. You can use Split.
You can later add those array elements to arraylist if you require.
String s="Hello I like Sports";
String[] words = s.split(" "); //getting into array
//adding array elements to arraylist using enhanced for loop
List<String> wordList=new ArrayList();
for(String str:words)
{
wordList.add(str);
}
First, you have to split the string, and :
if you want a List, use Arrays.asList
if you want an ArrayList, create one from this List.
Sample code :
final String str = "Hello I Like Sports";
// Create a List
final List<String> list = Arrays.asList(str.split(" "));
// Create an ArrayList
final ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(str.split(" ")));
Using Arrays.asList and the ArrayList constructor avoids you to iterate on each element of the list manually.
try this code was perfect work for get all word from .txt file
reader = new BufferedReader(
new InputStreamReader(getAssets().open("inputNews.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
for(String word :mLine.split(" ")) {
lst.add(word);
}
}

Adding item to multidimensional ArrayList

Hello only have a few hours with Java. (from Python)
I am trying to define a multidimensional array and populate it with the "add" method. however, I am seeing some bizarre results:
List<String[]> DrawInstructions = new ArrayList<String[]>();
String[] pair = {"",""};
pair[0]="UW";
pair[1]="100";
DrawInstructions.add(pair);
pair[0]="UM";
pair[1]="10";
DrawInstructions.add(pair);
pair[0]="UT";
pair[1]="50";
DrawInstructions.add(pair)
I expected DrawInstructions to end up with this:
[("UW,"100"),("UM","10"),("UT","50")]
But instead I am getting:
[("UT","50"),("UT","50"),("UT","50")]
I am sure this is pretty elemental but I cant figure it out, I have searched for a couple of hours. Thank you for any advice.
Problem is, you're changing the same array over and over — .add() does not create a copy for you. Try the following:
List<String[]> DrawInstructions = null;
String[] pair = {"",""};
pair[0]="UW";
pair[1]="100";
DrawInstructions.add(pair);
pair = new String[] {"",""};
pair[0]="UM";
pair[1]="10";
DrawInstructions.add(pair);
pair = new String[] {"",""};
pair[0]="UT";
pair[1]="50";
DrawInstructions.add(pair);
or, better then,
List<String[]> drawInstructions = new ArrayList<String[]>();
drawInstructions.add(new String[] {"UW", "100"});
drawInstructions.add(new String[] {"UM", "10"});
drawInstructions.add(new String[] {"UT", "50"});
which would be closer to Java naming standards, avoid NPEs, minimize local state, and be arguably more readable.
You are adding the same array (pair) three times. All you do is changing it's value(content).
Remember that java operates on references, not on the copies of the objects.
Try to create pair1, pair2, pair3.
You defined only one String[] pair = {"",""};
You edited the same object 3 times and added that to the list.
You could do that:
List<String[]> DrawInstructions = new ArrayList<String[]>();
String[] pair1 = {"",""};
pair1[0]="UW";
pair1[1]="100";
DrawInstructions.add(pair1);
String[] pair2 = {"",""};
pair2[0]="UW";
pair2[1]="100";
DrawInstructions.add(pair2);
....

ArrayList in java

ArrayList<String> veri1 = new ArrayList<String>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
How can I add veri2 to veri1 like one element? I mean, if I call veri.get(0), it returns veri2.
You should declare your list as a list of string arrays, not a list of strings:
List<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
veri1.add(veri2);
Note that in general it is better to declare your list as List instead of ArrayList, as this leaves you the freedom to switch to a different list implementation later.
You should use the List interface and generics (for Java >= 1.5). Depending on what you want to do you can use this:
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
List<String> veri1 = new ArrayList<String>();
veri1.addAll(Arrays.asList(veri2)); // Java 6
List<String[]> veri3 = new ArrayList<String[]>();
veri3.add(veri2);
You can't actually do this.
veri2 is an array of strings, veri1 is an arraylist of individual strings
Thus, doing veri1.get(0) should return a single string, not an array of strings.
I just saw (due to fm), that you have an ArrayList<String>. You can do:
ArrayList veri1 = new ArrayList();
veri1.add(veri2)
or
ArrayList<String[]> veri1 = new ArrayList<String[]>();
veri1.add(veri2)
You can also make ver1 a List, which gives you flexibility in changing implementations.
It all depends on whether or not you want your ArrayList to be of one type or if you need it to hold multiple types.
If you just need it to hold String arrays throughout your code, declare as stated above:
ArrayList<String[]> list1 = new ArrayList<String[]>();
then just add the String array to it as follows:
list1.add(stringArray);
If you want it to be dynamic, declare it with the object type:
ArrayList<Object> anythingGoes = new ArrayList<Object>();
and then you can add anything later on as well:
anythingGoes.add(stringArray);
anythingGoes.add(myAge);
anythingGoes.add(myName);
I think you mean this:
import java.util.Arrays;
ArrayList<String> veri1 = new ArrayList<String>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
veri1.addAll(Arrays.asList(veri2);
You pretty much just need to add the array to the ArrayList.
ArrayList<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"a", "b", "c"};
veri1.add(veri2);
System.out.println(veri1.size());
for(String[] sArray : veri1)
for(String s : sArray)
System.out.println(s);

Categories

Resources