2017-07-19 209 views
0

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

如果我想要更新所有价格为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; 
} 

感谢

+0

...您可以使用for循环并找到具有这些特定值的产品?可观察列表与普通列表的工作方式相同。 – Moira

+0

也许这个帮助,http://www.artima.com/lejava/articles/equality.html – dadan

回答

3

您可以使用Java 8的功能类型简洁,可读的代码:

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

products.forEach(product -> { 
     if (product.price == 1.49) product.price = 2.49; 
}); 

如果你想检索所有的产品具有一定的条件下,这样做:

products.stream().filter(product -> /* some condition */).collect(Collectors.toList()); 

此外,你可以简单的使用正常的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; 
} 

根据有效的Java,尽量限制变量的范围 - 避免在循环之外声明迭代器。

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

+0

它的工作原理。非常感谢 – Joe

1

只要使用这个正常Iterator。您还需要创建getters and setters

for (Iterator i = products.iterator(); i.hasNext();) 
    Product p = i.next(); 

    if (p.getName().equals("Corn")) { 
     i.remove(); 
    } else if (p.getPrice() == 1.49) { 
     p.setPrice(2.49); 
    } 
} 
相关问题