在Java 8中使用嵌套的for循环找出给定的差异 [英] Using nested for loops in Java 8, to find out given difference

查看:265
本文介绍了在Java 8中使用嵌套的for循环找出给定的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我正在使用嵌套的for循环,并且有一些条件会破坏内部的for循环,从而提高了这段代码的性能.

I have below code where I am using nested for loops and I have some condition that breaks the inner for loop, and this improves the performance of this code.

假设提供的列表已经排序.现在,我想找到其差等于某个值的元素数量,例如k.

Assume that the list provided is already sorted. Now I want to find the number of elements whose difference is equal to some value say k.

public static int getCount(List<Integer> list, int k) {
    int result = 0;
    for (int i = 0; i < list.size(); i++) {
        for (int j = i + 1; j < list.size(); j++) {
            if (list.get(j) - list.get(i) > k) {
                break;
            }
            if (list.get(j) - list.get(i) == k) {
                result++;
            }
        }
    }
    return result;
}

现在使用Java 8流的逻辑相同,这里跳过了我使用过return语句的内循环,但是由于内循环没有中断,因此性能没有得到改善.

Now the same logic using Java 8 streams, here to skip inner loop I have used return statement, but as the inner loop is not broken the performance is not improved.

public static int getCount(List<Integer> list, int k) {
    int[] result = { 0 };
    IntStream.range(0, list.size()).forEach(i -> {
        IntStream.range(i + 1, list.size()).forEach(j -> {
            if (list.get(j) - list.get(i) >= k)
                return;
            if (list.get(j) - list.get(i) == k) {
                result[0]++;
            }
        });
    });
    return result[0];
}

推荐答案

将内部IntStream.forEach()替换为以下内容,并查看其是否按预期工作:

Replace your inner IntStream.forEach() with the following and see if it works as expected:

IntStream.range(i + 1, list.size())
        .filter(j -> list.get(j) - list.get(i) == k)
        .forEach(j -> result[0]++);

这篇关于在Java 8中使用嵌套的for循环找出给定的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆