Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a single object from a list using stream

Tags:

java

java-8

I have a list of objects. I need to update a single object from the list that match my filter. I can do something like below:

List<MyObject> list = list.stream().map(d -> {
    if (d.id == 1) {
        d.name = "Yahoo";
        return d;
    }
    return d;
});

But my worry is i am like iterating through the whole list which may be up to 20k records. I can do a for loop then break, but that one I think also will be slow.

Is there any efficient way to do this?

like image 641
iPhoneJavaDev Avatar asked Dec 18 '22 17:12

iPhoneJavaDev


1 Answers

Use findFirst so after finding the first matching element in the list remaining elements will not be processed

Optional<MyObject> result = list.stream()
                                .filter(obj->obj.getId()==1)
                                .peek(o->o.setName("Yahoo"))
                                .findFirst();

Or

  //will not return anything but will update the first matching object name

                              list.stream()
                              .filter(obj->obj.getId()==1)
                              .findFirst()
                              .ifPresent(o->o.setName("Yahoo"));
like image 134
Deadpool Avatar answered Jan 13 '23 19:01

Deadpool