Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to replace a simple java for loop (with index) with java 8 stream

I want to have failfast behavior for any unsuccessful response and if all go successful then I return the last successful response as shown in following code.

for(int i=0;i<input.size(); i++){
   Data data = service.getData(input.get(i));
   if(data.isSuccessful() && i==input.size()-1){
      return data;
   }else if(!data.isSuccessful()){
    return data;
    }else{
    return null;
  }
 }

I tried to replace above mention code with streams but not been able to do so far.Main issue is that I am not able to imitate i(index) variable behavior in java8 stream code.

resp = input.stream().map((input)->{service.getData()}).filter(
(resp)->{
     if(!resp.isSuccessful())
        return true; 
     else if(resp.isSuccessful() && last resp)//if somehow I figure out last element
        return true;
     else 
        return false;}).findFirst();
like image 784
Bharat Bhagat Avatar asked Jul 21 '26 05:07

Bharat Bhagat


1 Answers

There is no need for external libraries.

return IntStream.range(0, input.size())
.mapToObj(i -> {
    Data data = service.getData(input.get(i));
    if (!data.isSuccessful() || i == input.size() - 1) {
        return Optional.of(data);
    }
    return Optional.<Data>empty();
})
.filter(Optional::isPresent)
.findFirst()
.orElse(null);
  • More information about looping with indices: Is there a concise way to iterate over a stream with indices in Java 8?
  • Consider returing the Optional, rather than the result or null

Complete example (compilable):

import java.util.Optional;
import java.util.stream.IntStream;

class Data {
    public boolean isSuccessful() {return false;}
}
class Input {
    public Object get(int i) {return null;}
    public int size() {return 0;}
}
class Service {
    public Data getData(Object object) {return null;}
}
public class T {
    public static void main(String[] args) {method();}

    protected static Optional<Data> method() {
        Input input = new Input();
        Service service = new Service();

        return IntStream.range(0, input.size())
                .mapToObj(i -> {
                    Data data = service.getData(input.get(i));
                    if (!data.isSuccessful() || i == input.size() - 1) {
                        return Optional.of(data);
                    }
                    return Optional.<Data>empty();
                })
                .filter(Optional::isPresent)
                .findFirst()
                .orElse(null);
    }
}
like image 65
slartidan Avatar answered Jul 23 '26 10:07

slartidan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!