2017-07-19 210 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); 
    } 
} 
相關問題