简体   繁体   中英

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<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:

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.

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.

use a tmp variable to store the vitC.next() and in case it match the condition you can still add 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 (Fruit thisFruit : fruit) {
    if (thisFruit.contains("Vitamin C")) {
        vitCfruit.add(thisFruit);
    }
}

In Java 8, this is simple with lambdas:

List<Foods> vitCfruit = fruit.stream()
    .filter(f -> f.contains("Vitamin C"))
    .collect(Collectors.toList());

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