给定以下代码
public class StreamSpliteratorTest {
public static void main(String[] args) {
var ids = Stream.generate(() -> RandomStringUtils.randomAlphanumeric(5))
.limit(100)
.collect(Collectors.toList());
get(ids)
.forEach(resultMap -> {
System.out.printf("Got result map with size %s%n", resultMap.size());
});
}
static Stream<Map<String, String>> get(Collection<String> ids) {
var remainginIds = new HashSet<>(ids);
var initialCount = remainginIds.size();
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(new Iterator<>() {
@Override
public boolean hasNext() {
return !remainginIds.isEmpty();
}
@Override
public Map<String, String> next() {
Map<String, String> result = Map.of();
try {
var chunk = remainginIds.stream().limit(10).collect(Collectors.toSet());
remainginIds.removeAll(chunk);
result = fetch(chunk).get(5, TimeUnit.SECONDS);
System.out.printf("%s of %s ids done%n", initialCount - remainginIds.size(), initialCount);
} catch (Exception e) {
System.err.printf("Request thread pool was interrupted: %s%n", e.getMessage());
}
return result;
}
}, Spliterator.IMMUTABLE), true);
}
static CompletableFuture<Map<String, String>> fetch(Collection<String> ids) {
var delay = CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS);
return CompletableFuture
.supplyAsync(() -> ids.stream().collect(Collectors.toMap(e -> e, e -> e)), delay);
}
}
结果是
10 of 100 ids done
20 of 100 ids done
30 of 100 ids done
40 of 100 ids done
50 of 100 ids done
60 of 100 ids done
70 of 100 ids done
80 of 100 ids done
90 of 100 ids done
100 of 100 ids done
Got result map with size 10
Got result map with size 10
Got result map with size 10
Got result map with size 10
Got result map with size 10
Got result map with size 10
Got result map with size 10
Got result map with size 10
Got result map with size 10
Got result map with size 10
我很困惑为什么一次执行的结果next()
没有立即传递给调用代码中的下一个使用者?我希望这会导致以下输出:
10 of 100 ids done
Got result map with size 10
20 of 100 ids done
Got result map with size 10
30 of 100 ids done
Got result map with size 10
40 of 100 ids done
Got result map with size 10
50 of 100 ids done
Got result map with size 10
60 of 100 ids done
Got result map with size 10
70 of 100 ids done
Got result map with size 10
80 of 100 ids done
Got result map with size 10
90 of 100 ids done
Got result map with size 10
100 of 100 ids done
Got result map with size 10
我在这里做错了什么?