如何删除或更新ObservableList中的某些行

Joe*_*Joe 0 java javafx javafx-2

我有一个关于使用单个元素检测和删除并更新列表中某些行的问题。如果我只知道一个元素“玉米”,该如何从列表中删除它。

而且,如果我想将价格为1.49到2.49的所有产品更新,还应如何做。

    ObservableList<Product> products = FXCollections.observableArrayList();
    products.add(new Product("Laptop", 859.00, 20));
    products.add(new Product("Bouncy Ball", 2.49, 198));
    products.add(new Product("Toilet", 9.99, 74));
    products.add(new Product("The Notebook DVD", 19.99, 12));
    products.add(new Product("Corn", 1.49, 856));
    products.add(new Product("Chips", 1.49, 100));

    if (products.contains("Corn")){  
        System.out.println("True");
    }
    else System.out.println("False");


class Product {
    Product(String name, Double price, Integer quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }
    private String name;
    private Double price;
    private Integer quantity;
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Moi*_*ira 5

您可以将Java 8的功能类型用于简明易懂的代码:

products.removeIf(product -> product.name.equals("Corn"));

products.forEach(product -> {
        if (product.price == 1.49) product.price = 2.49;
});
Run Code Online (Sandbox Code Playgroud)

如果要检索具有特定条件的所有产品,请执行以下操作:

products.stream().filter(product -> /* some condition */).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

此外,您可以简单地使用normal Iterator

for (Iterator<Product> i = products.iterator(); i.hasNext();) {
    Product product = i.next();
    if (product.name.equals("Corn")) i.remove();
    else if (product.price == 1.49) product.price = 2.49;
}
Run Code Online (Sandbox Code Playgroud)

按照有效Java的规定,请尽量限制变量的范围-避免在循环外部声明迭代器。

您不能在此处使用for-each循环,因为在for-each循环中删除将导致ConcurrentModificationException