4

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?
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
CSnerd
  • 2,129
  • 8
  • 22
  • 45
  • It's possible in VBScript and other languages, using the "Execute (sString)" command. But I don't think Java has such a command. – BrettFromLA Jul 23 '14 at 22:28
  • In general, if you have that many `String` variables, you're doing something wrong. Always consider storing them in some sort of array or list structure or a `Map`. – ajb Jul 23 '14 at 22:30
  • 1
    Where do these String variables come from? And why do you have 100 different variables that only differ in name by a number? This begs for an array! – Code-Apprentice Jul 23 '14 at 22:31

6 Answers6

18

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

markspace
  • 10,621
  • 3
  • 25
  • 39
4

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");
Noyal
  • 223
  • 2
  • 7
1

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
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

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);
AlexR
  • 2,412
  • 16
  • 26
0

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

ajb
  • 31,309
  • 3
  • 58
  • 84
0

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());}};
xavierz
  • 335
  • 1
  • 11