2017-07-19 6 views
0

単一要素を使用して、リスト内の特定の行を検出および削除して更新する際に問題があります。 "Corn"という要素がひとつしかわからない場合、どうすればこのリストから削除できますか?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

:あなたは、特定の条件ですべての製品を検索したい場合は

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も作成する必要があります。

あなたが簡潔で、読みやすいコードは、Java 8の機能タイプを使用することができます
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); 
    } 
} 
関連する問題