简体   繁体   English

将列表从数组列表存储到字符串

[英]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).我想所有的显示从字符串内容ArrayList ,但规模ArrayList是未知的(使用过Android Studio)。 So for example:例如:

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

After some operations, now the story ArrayList contained some information, such as:经过一些操作,现在故事ArrayList包含了一些信息,例如:

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.我不知道操作后水果和蔬菜的ArrayList是多长时间。 But I know that the fruit and veg has the same size of ArrayList .但我知道水果和蔬菜的大小与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) .我觉得它需要使用for循环通过调用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?但是我如何独立存储这个fruit(0), fruit(1),...,fruit(i)列表中的每一个,以便我可以将它们连接在一起成为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.所有教程都继续使用printlnlogd ,因此它可以打印每个 for 循环的fruit(i)veg(i) ,但并没有真正将fruit(i)veg(i)为独立使用的变量.

Thank you for your help!感谢您的帮助!

I would use StringBuilder to build the string.我会使用StringBuilder来构建字符串。

Since both lists have the same number of elements, use a simple for loop to iterate both lists.由于两个列表具有相同数量的元素,因此使用简单的for循环来迭代两个列表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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