[英]How do you add elements from one ArrayList to another?
So I have one ArrayList of fruits which has the name of the fruit and what its predominant vitamin is:所以我有一个水果的 ArrayList,它有水果的名字和它的主要维生素是什么:
ArrayList<Foods> fruit;
public Fruit() {
fruit = new ArrayList<Foods>();
fruit.add(new Foods("Orange", "Vitamin C"));
}
etc..等等..
I want to add all the fruits with vitamin C to another array list so I iterated over them using:我想将所有含有维生素 C 的水果添加到另一个数组列表中,因此我使用以下方法迭代它们:
Iterator vitC = fruit.iterator();
while (vitC.hasNext()) {
if (vitC.next().contains("Vitamin C")) {
vitCfruit.add(vitC.next());
}
}
However this adds the next value, so if apple was after orange in the list it would add apple to the next ArrayList instead of orange.然而,这会添加下一个值,所以如果苹果在列表中的橙色之后,它会将苹果添加到下一个 ArrayList 而不是橙色。
I'll ignore the apparent error in the code.我将忽略代码中的明显错误。 In order to work with the element on the list you should do the following:
为了使用列表中的元素,您应该执行以下操作:
Iterator vitC = fruit.iterator();
while (vitC.hasNext()) {
Foods x = vitC.next();
if (x.contains("Vitamin C")) { // should look for a Foods object here!!!
administrators.add(x);
}
}
the vitC.next() in the 'if' you declared will work, but you will not be accessing the same element in the next line when add it to the new list.您声明的“if”中的 vitC.next() 将起作用,但将其添加到新列表时,您将不会访问下一行中的相同元素。
use a tmp variable to store the vitC.next() and in case it match the condition you can still add ot..使用 tmp 变量来存储 vitC.next() ,如果它符合条件,您仍然可以添加 ot..
Iterator vitC = fruit.iterator();
while (vitC.hasNext()) {
tmp = vitC.next();
if (tmp.contains("Vitamin C")) { // should look for a Foods object here!!!
administrators.add(tmp);
}
}
The enhanced for loop makes this straightforward:增强的 for 循环使这变得简单:
for (Fruit thisFruit : fruit) {
if (thisFruit.contains("Vitamin C")) {
vitCfruit.add(thisFruit);
}
}
In Java 8, this is simple with lambdas:在 Java 8 中,这对于 lambda 很简单:
List<Foods> vitCfruit = fruit.stream()
.filter(f -> f.contains("Vitamin C"))
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.