我有以下 API 调用
cloudwatchClient.deleteInsightRules(
new DeleteInsightRulesRequest().withRuleNames(existingRuleNames));
失败是因为
[exec] Exception in thread "main" com.amazonaws.services.cloudwatch.model.MissingRequiredParameterException: BATCH_REQUEST_TOO_LARGE: Batch size cannot exceed 20 items. (Service: AmazonCloudWatch; Status Code: 400; Error Code: MissingRequiredParameterException; Request ID: 0f820dc2-38b8-11e9-8465-3718764429f1)
现在我明白,我必须以 20 个为一组多次调用 cloudwatch 的 deleteInsight 规则。
所以从概念上讲,我正在寻找
existingRuleNames
.stream().
.chunkIntoSizeOf(20) // This is an imaginary method, i need to convert it into something concrete
.foreach(chunk -> cloudwatchClient.deleteInsightRules(
new DeleteInsightRulesRequest().withRuleNames(chunk));
现在我在 java 8 流 api 中找不到任何允许我将列表划分和处理为 block 的内容。有点像 scala 分组功能 Split list into multiple lists with fixed number of elements 。
有人可以帮我解决这个问题吗?谢谢。我当然可以使用命令式风格并使用子列表,但如果可以的话我更愿意避免这种情况。
最佳答案
在下面的 forEach 中,您可以对 block 执行任何您想要执行的操作:
//my list of 30 strings that needs to be processed (existingRuleNames in your case):
List<String> list = IntStream.range(0, 30).mapToObj(String::valueOf).collect(Collectors.toList());
AtomicInteger prev = new AtomicInteger(0);
IntStream.range(1, (int) (20 * (Math.ceil(Math.abs(list.size() / 20.0)))))
.filter(i -> i % 20 == 0 || i == list.size())
.forEach(i -> {
List<String> chunk = list.subList(prev.get(), i);
System.out.println("Processing " + chunk);
prev.set(i);
});
输出:
Processing [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Processing [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
<小时/>
所以你的代码应该类似于:
List<String> existingRuleNames = ...;
AtomicInteger prev = new AtomicInteger(0);
IntStream.range(1, (int) (20 * (Math.ceil(Math.abs(existingRuleNames.size() / 20.0)))))
.filter(i -> i % 20 == 0 || i == existingRuleNames.size())
.forEach(i -> {
List<String> chunk = existingRuleNames.subList(prev.get(), i);
cloudwatchClient.deleteInsightRules(
new DeleteInsightRulesRequest().withRuleNames(chunk));
prev.set(i);
});
关于java - 如何在Java流中处理时将一个列表分割为多个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54859850/