![](/img/trans.png)
[英]What is the proper way of replacing a nested for loop with streams in Java 8?
[英]What is the proper way to write this with streams?
如果異常處理按預期工作,則以下代碼應能實現所需的功能:
XVector position = new XVector();
IntStream.range(0, desired_star_count).forEach(a -> {
// Try to find a position outside the margin of other stars.
try
{
IntStream.range(0, XStarField.patience).forEach(b -> {
position.random(size);
error:
{
for (XVector point : this.positions)
if (position.sub(point).get_magnitude() < min_star_margin)
break error;
throw new XStarField.Found();
}
});
}
catch (XStarField.Found event)
{
this.positions.add(position.copy());
this.colors.add(Math.random() < 0.5 ? XColor.RED : XColor.BLUE);
}
});
不幸的是,生成了以下兩個錯誤:
Error:(33, 25) java: unreported exception XStarField.Found; must be caught or declared to be thrown
Error:(37, 13) java: exception XStarField.Found is never thrown in body of corresponding try statement
如果我要用Python編寫相同的代碼,結果可能是這樣的:
position = XVector()
for a in range(desired_star_count):
for b in range(self.patience):
position.random(size)
for point in self.positions:
if abs(position - point) < min_star_margin:
break
else:
self.position.append(position.copy())
self.colors.append(XColor.RED if random.random() < 0.5 else XColor.BLUE)
break
如果不使用流,編寫起來很簡單,但是我認為這是一次學術學習活動,可以更好地理解它們。 有沒有辦法編寫代碼來替換計數循環並像嘗試那樣在其位置使用流?
您可以改用以下代碼。 它既避免了例外,又避免了其實現的中斷。 通過正確應用流,該算法變得更易於閱讀和理解。
XVector position = new XVector();
IntStream.range(0, DESIRED_STAR_COUNT).forEach(a -> {
// Try to find a position outside the margin of other stars.
IntStream.range(0, PATIENCE).filter(b -> {
position.random(size);
return !this.positions.stream().anyMatch(point -> position.sub(point).getMagnitude() < MIN_STAR_MARGIN);
}).findFirst().ifPresent(b -> {
this.positions.add(position.copy());
this.colors.add((XColor) XRandom.sChoice(RED_STAR, BLUE_STAR));
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.