简体   繁体   English

在ArrayList中查找和修改特定元素

[英]Find and modify specific element in ArrayList

is some elegant way to find and modify some specific object in java? Java中查找和修改某些特定对象的一种优雅方法是什么? I have method like that: 我有这样的方法:

public update(MyObj o) {
   for (MyObj objToModify: DATA) {
       if (objToModify.getId() == o.getId()) {
           objToModify.setName(o.getName());
           // and so on ...
       }
   }
}

Is possible to rewrite to lambda for example, or some other feature of Java 8? 例如,是否可以重写为lambda或Java 8的某些其他功能? I had a lot of properties so I will prefer some option where I couldn't write manually set up all of new properties. 我有很多属性,因此我会选择一些无法手动设置所有新属性的选项。

You can do it in the following way, this will go over the whole stream and update elements even if there is more then one matching: 您可以通过以下方式进行操作,即使存在多个匹配项,这也将遍历整个流并更新元素:

DATA.stream().filter(a -> a.getId() == o.getId()).forEach(a -> a.setName(o.getName()));

Or if you are sure that you only need to update one element: 或者,如果您确定只需要更新一个元素:

DATA.stream().filter(a -> a.getId() == o.getId()).
    findAny().ifPresent(a -> a.setName(o.getName()));

Both solutions will throw NullPointerException if DATA has null elements the same as your original solution, if it's a posiibility and you want to prevent it you need to also check that a is not null in filter . 如果DATA具有与原始解决方案相同的null元素,则这两种解决方案都将引发NullPointerException ;如果这是可能的,并且您想防止出现这种情况,则还需要检查filtera是否不是null。

You can use lambda expression to do what you are trying to do 您可以使用lambda表达式执行您要尝试执行的操作

public update(MyObj o) {

    DATA.forEach(objToModify -> {

        if (objToModify.getId() == o.getId()) {
            objToModify.setName(o.getName());
            // and so on ...
        }
    });   
}

although i am not sure if using lambda expression in your case will be more efficient than using for-each loop. 尽管我不确定在您的情况下使用lambda expression是否会比使用for-each循环更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM