如何使用Java流(streams)编写包含循环、if/else和return语句的代码。

huangapple go评论76阅读模式
英文:

How can we write code having loop, if/else and return statement using java streams

问题

我需要使用Java Streams来处理这段代码。

IntStream.range(0, maxWaitTimeForRegistration).anyMatch(i -> {
    if (service.getRefreshDeviceDetails(BaseTest.equalsIgnoreCase("Disconnected"))) {
        return true;
    }
    WaitinSeconds(5);
    return false;
});

但是由于anyMatch方法返回的是布尔值,所以这并不正确。

英文:

I need to use java streams for this piece of code.

for(int i =0 ;i< maxWaitTimeForRegistration ; i++) {
            if (service.getRefreshDeviceDetails(BaseTest.equalsIgnoreCase("Disconnected")) {
                return true;
            }
            WaitinSeconds(5);
        }

I tried using this

IntStream.range(0, maxWaitTimeForRegistration).forEach(j -> {
           if (service.getRefreshDeviceDetails(BaseTest.equalsIgnoreCase("Disconnected")) {
                return true;
            }
            WaitinSeconds(5);
        }
        });

But since forEach method is returning void, so It's not right.

答案1

得分: 1

Technically it could be done this way:

private static boolean retryStream() {
    return IntStream.range(0, MAX_WAIT_TIME_FOR_REGISTRATION)
            .peek(tryNum -> waitSeconds(4))
            .anyMatch(tryNum -> service.getRefreshDeviceDetails(BaseTest.equalsIgnoreCase("Disconnected")));
}

But the Stream API is not really intended for blocking retries. Also, this way the stream is waiting even before the first check... so you would probably need to use another if condition check before the stream retry.


A working solution:

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

class Scratch {

    private static final int     MAX_WAIT_TIME_FOR_REGISTRATION = 4;
    private static final Service service                        = new Service();
    private static String        BaseTest                       = "Test";

    public static void main(String[] args) {
        // change the value asynchronously
        new Thread(() -> {
            waitSeconds(4 * 2);
            BaseTest = "Disconnected";
        }).start();

//        System.out.println(retry());
        System.out.println(retryStream());
    }

    private static boolean retry() {
        for(int i = 0; i< MAX_WAIT_TIME_FOR_REGISTRATION; i++) {
            if (service.getRefreshDeviceDetails(BaseTest.equalsIgnoreCase("Disconnected"))) {
                return true;
            }
            waitSeconds(4);
        }
        return false;
    }

    private static boolean retryStream() {
        return IntStream.range(0, MAX_WAIT_TIME_FOR_REGISTRATION)
                .peek(tryNum -> waitSeconds(4))
                .anyMatch(tryNum -> service.getRefreshDeviceDetails(BaseTest.equalsIgnoreCase("Disconnected")));
    }

    private static void waitSeconds(int seconds) {
        try {
            Thread.sleep(TimeUnit.SECONDS.toMillis(seconds));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

}

class Service {

    public boolean getRefreshDeviceDetails(boolean disconnected) {
        return disconnected;
    }
}
英文:

Technically it could be done this way:

private static boolean retryStream() {
	return IntStream.range(0, MAX_WAIT_TIME_FOR_REGISTRATION)
			.peek(tryNum -&gt; waitSeconds(4))
			.anyMatch(tryNum -&gt; service.getRefreshDeviceDetails(BaseTest.equalsIgnoreCase(&quot;Disconnected&quot;)));
}

But the Stream API is not really intended for blocking retries. Also, this way the stream is waiting even before the first check... so you would probably need to use another if condition check before the stream retry.


A working soution:

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
class Scratch {
private static final int     MAX_WAIT_TIME_FOR_REGISTRATION = 4;
private static final Service service                        = new Service();
private static String        BaseTest                       = &quot;Test&quot;;
public static void main(String[] args) {
// change the value asynchronously
new Thread(() -&gt; {
waitSeconds(4 * 2);
BaseTest = &quot;Disconnected&quot;;
}).start();
//		System.out.println(retry());
System.out.println(retryStream());
}
private static boolean retry() {
for(int i = 0; i&lt; MAX_WAIT_TIME_FOR_REGISTRATION; i++) {
if (service.getRefreshDeviceDetails(BaseTest.equalsIgnoreCase(&quot;Disconnected&quot;))) {
return true;
}
waitSeconds(4);
}
return false;
}
private static boolean retryStream() {
return IntStream.range(0, MAX_WAIT_TIME_FOR_REGISTRATION)
.peek(tryNum -&gt; waitSeconds(4))
.anyMatch(tryNum -&gt; service.getRefreshDeviceDetails(BaseTest.equalsIgnoreCase(&quot;Disconnected&quot;)));
}
private static void waitSeconds(int seconds) {
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(seconds));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class Service {
public boolean getRefreshDeviceDetails(boolean disconnected) {
return disconnected;
}
}

huangapple
  • 本文由 发表于 2020年8月17日 18:10:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63448732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定