在ArrayList中查找对象并将其删除

时间:2016-04-11 00:34:23

标签: java arraylist

我有一个名为Items的ArrayList。

我想循环遍历ArrayList并搜索名称,价格。如果名称&价格匹配来自用户的输入并且价格高于之前,我想删除旧对象(包含名称和价格,然后将新项目(从输入)添加到ArrayList。

基本上,如果我的ArrayList包含:(Milk,15)

以下输入是Milk,19

新的ArrayList现在包含:(Milk,19)

来自评论的

编辑:如何声明所选对象并将其删除?

System.out.println("Item name: ");

String name = input.nextLine();

System.out.println("Price: ");

int price = input.nextInt();

Item newItem = (Name, price);



for (Items i: itemList) {

    if(i.getName().contains(name) && i.getPrice()==price)) {


        // here declare object which contains name & price

        //Not sure if below would work but something along these lines

        if(price > object.getPrice()) {

            itemList.remove(object above)

            //and then

            itemList.add(newItem)
        }
    }
}

2 个答案:

答案 0 :(得分:2)

这样做的一个合理巧妙的方法是使用removeIf方法,然后添加新项目,如果有任何删除。如果删除了任何内容,则removeIf会返回true

if(items.removeIf(item -> item.getName().equals(name) && item.getPrice() > price))
    items.add(new Item(name, price));

注意:此代码需要Java 8

答案 1 :(得分:0)

我会说你应该使用Map<String, Integer>代替。 Map / Dictionary / etc是存储键/值对的东西,它的意思就是这类东西:

Map<String, Integer> values = new HashMap<>();

//example logic of utilizing the map to replace values and store the highest
public int addBet(String name, int amount) {
    //in Java 7 or less:
    Integer old = values.get(name); //get the old value
    if (old == null) {
        old = amount; //if there was no old value, we'll use the new one
    } else {
        old = Math.max(old, amount); //if there was a value, use the highest
    }
    return values.put(name, old); //set the amount
    //In Java 8, we have #compute for this instead:
    return values.compute(name, old -> old == null ? amount : Math.max(old, amount));
}

因此,使用此功能,我们可以通过#addBet看到最高值,它会演示地图用法:

addBet("Bob", 10); //returns 10
addBet("Foo", 14); //14
addBet("Bob", 22); //22
addBet("Bob", 15); //22
values.get("Bob"); //22
values.get("Foo"); //14

此外,这比每次迭代整个列表更有效。