简体   繁体   English

用 Java 流替换嵌套循环

[英]Replace nested loop with Java streams

how can I replace the following code with Streams?如何用 Streams 替换以下代码?

 Annotation[][] annotations = context.getMethod().getParameterAnnotations();
        Object[] parameterValues = context.getParameters();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < annotations.length; i++) {
            for (int j = 0; j < annotations[i].length; j++) {
                if (annotations[i][j] instanceof CacheKey && parameterValues[i] != null) {
                    stringBuilder.append(parameterValues[i]);
                    break;
                }
            }
        }

I can easily use flatmap to get data from the first array of array, but I have no idea how to get the position to fetch the right value from parameterValues[i].我可以轻松地使用 flatmap 从数组的第一个数组中获取数据,但我不知道如何让 position 从 parameterValues[i] 中获取正确的值。

Thanks谢谢

You could zip annotations with paremeterValues using some known method , but you should also ask yourself "is this gonna be more readable and better that it already is?".您可以使用一些已知的方法使用参数值对paremeterValues进行annotations ,但您也应该问自己“这是否会比它已经更具可读性和更好?”。 Short answer - no.简短的回答 - 不。

You compare parameterValues[i] != null in the inner loop when you can actually extract it level higher (Is this even needed? Ain't parameters not null by default?).当您实际上可以将其提取到更高级别时,您可以在内部循环中比较parameterValues[i] != null (这甚至需要吗?默认情况下参数不是 null 吗?)。 You could also replace the inner loop with for-each, or even better refactor to simple matchAny() on stream or (the best) use getAnnotation() .您还可以用 for-each 替换内部循环,甚至更好地重构为 stream 上的简单matchAny()或(最好)使用getAnnotation() Check also if you can get annotations directly from Parameter, so that it would boil down to a simple:还要检查您是否可以直接从 Parameter 获取注释,以便归结为一个简单的:

StringBuilder sb = new StringBuilder();
for (var param : context.getParameters()) {
    if (param != null // is it needed ?
        && param.getAnnotation(CacheKey::class) != null)
        sb.append(param);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM