简体   繁体   中英

Storing a list to a string from an arraylist

I am trying to display all the String content from an ArrayList but the size of the ArrayList is unknown (using Android Studio). So for example:

fruit = new ArrayList<>()
veg = new ArrayList<>()

After some operations, now the story ArrayList contained some information, such as:

fruit = {"apple", "orange", "banana", "peach",...};
veg = {"cucumber", "spinach", "pumpkin", "broccoli",...};

I do not know how long the ArrayList of fruit and veg are after the operations. But I know that the fruit and veg has the same size of ArrayList . I want to store each of the list to be like:

fruitOne = fruit(0), fruitTwo = fruit(1), fruitThree = fruit(2),...
vegOne = veg(0), vegTwo = veg(1), vegThree = veg(2),...

Then I want to display them together as a String so that I can have a string such as:

String myStore = "I am selling" + fruitOne + " and " + vegOne + "/n" + fruitTwo + " and " + vegTwo + "/n" + fruitThree + " and " + vegThree"...;

I feel like it needs to use for loops to pull each of the list one by one by calling fruit(0), fruit(1),...,fruit(i) . But how do I store each of this list of fruit(0), fruit(1),...,fruit(i) independently so that I can concatenate them together to become one String of myStore?

All the tutorial kept on taking about println or logd , so it can print the fruit(i) or veg(i) each for loop, but not really storing the fruit(i) or veg(i) as a variable to be used independently.

Thank you for your help!

I would use StringBuilder to build the string.

Since both lists have the same number of elements, use a simple for loop to iterate both lists.

List<String> fruit = Arrays.asList("apple", "orange", "banana", "peach");
List<String> veg = Arrays.asList("cucumber", "spinach", "pumpkin", "broccoli");
StringBuilder sb = new StringBuilder();
sb.append("I am selling ");
int count = fruit.size();
for (int i = 0; i < count; i++) {
    sb.append(fruit.get(i));
    sb.append(" and ");
    sb.append(veg.get(i));
    sb.append("\n");
}
System.out.println(sb);

Running the above code produces the following string:

I am selling apple and cucumber
orange and spinach
banana and pumpkin
peach and broccoli

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM