F0cus
F0cus

Reputation: 625

Rewrite traditional for loop to streams.map java 8

i am trying to test a Rest API PUT request. It is a spring boot application. PUT request is used to do an update in the existing list of objects

traditional way of writing is working.

data is the data in the memory - which is a List<Bean> and name (string type) is the key to find the object in the data and objectBean is the one to replace once we find with the key(that is name)

public void update(Bean objectBean, String name) {

    for(int i = 0; i < data.size() ; i++) {
        Bean l = data.get(i);
        if(l.getName().equals(name)) {
            data.set(i, objectBean);
            return;
        }
    }   

};

but i tried to write using Stream in java 8 . below is the code

Data.stream().map(p -> p.getName().equals(name) ? objectBean: p );

but this gives empty list.

Upvotes: 0

Views: 422

Answers (3)

lczapski
lczapski

Reputation: 4120

Using streams here makes code only more complicated.

If you really wants you can introduce it to find the index i value. After that you can do the replacement.

IntStream.range(0, data.size())
    .filter(i -> data.get(i).getName().equals(name)).findFirst()
    .ifPresent(i -> data.set(i, objectBean));

Upvotes: 3

tanyehzheng
tanyehzheng

Reputation: 2221

return data.stream()
    .filter(bean -> bean.getName().equals(name))
    .findAny()

Upvotes: 0

Nimrod Sadeh
Nimrod Sadeh

Reputation: 351

Given that data is some List with Bean objects, you'd need to return your collected stream:

return data.stream()
  .map(bean -> bean.getName().equals(name) ? objectBean : bean)
  .collect(Collectors.toList());

If data is a non-empty Iterable then the output must be as well as map takes a Function object. However, this is not a good use case for the Stream API:

Firstly, streams are designed for side-effect-free purposes (i.e., creating new data structures rather updating them). The stream API supports forEach(Consumer<super T>) which is designed for side effects, but so do many other collections, in fact, all Iterables, whereas the immutable operations such as map and flatMap are not.

Second, I can't see the rest of your program, but at least in this snippet you seem to be updating your data structure based on the name, and you assume the name is unique because you stopped as soon as you reached the first Bean with the name you're looking for. Consider using Map<String, Bean> as your data structure.

Lastly, streams are lazy data structures, meaning that all the chained operations get computed when you collect. This provides incentive to chain a lot of computations together - chaining just a single map doesn't give you any performance advantages (tho it does give you referential transparency).

Upvotes: 0

Related Questions