简体   繁体   中英

How do I remove items from an ArrayList of specific property?

I created an ArrayList:

ArrayList<Fruit> fruit = new ArrayList<Fruit>();

and added elements:

fruit.add(new Fruit("apple", "red");
fruit.add(new Fruit("orange", "orange");
fruit.add(new Fruit("strawberry", "red");

I want to remove all the instances of red fruits. Can someone help me figure out how to do this, please? Thanks in advance.

for (Iterator<Fruit> iter = list.listIterator(); iter.hasNext(); ) {
    Fruit f = iter.next();
    if (f.getColor().equalsIgnoreCase("red")) {
        iter.remove();
    }
}

Assuming you have a getter method in Fruit class for color field.

In Java 5.0+ you can do

for(Iterator<Fruit> iter = fruit.iterator(); iter.hasNext(); )
    if (iter.next().getColour().equals("red"))
         iter.remove();

In Java 8 you can create a new List with

List<Fruit> nonRed = fruit.stream()
                          .filter(f -> !f.getColour().equals("red"))
                          .collect(Collectors.toList());

In addition to the other Java 8 solutions there is an in-place removeIf in the Collection interface.

List<Fruit> fruit = new ArrayList<>();

fruit.add(new Fruit("apple", "red"));
fruit.add(new Fruit("orange", "orange"));
fruit.add(new Fruit("strawberry", "red"));

System.out.println(fruit);
fruit.removeIf(f -> f.color.equals("red"));
System.out.println(fruit);

The common way(syntax) will look like the below.

for (Iterator<Object> it = data.iterator(); it.hasNext();) {
if (it.next().getCaption().contains("_Hardi")) {
    it.remove();
}
}

In Java 8 you can do this:

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Learning {

    public static class Fruit {
        public final String name;
        public final String colour;

        public Fruit(String name, String colour) {
            this.name = name;
            this.colour = colour;
        }
    }

    @Test
    public void x() {
        ArrayList<Fruit> fruit = new ArrayList<Fruit>();
        fruit.add(new Fruit("apple", "red"));
        fruit.add(new Fruit("orange", "orange"));
        fruit.add(new Fruit("strawberry", "red"));

        List<Fruit> notRed = 
                fruit
                        .stream()
                        .filter(f -> !f.colour.equals("red"))
                        .collect(Collectors.<Fruit>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