简体   繁体   English

Java:是否可以使用“嵌套”映射方法(java.util.stream)?

[英]Java : is it possible to have 'nested' map methods (java.util.stream)?

Given an array of ints (eg [8, 7, 5, 3] ), I want to verify that the numbers are pairwise co-primes. 给定一个整数数组(例如[8, 7, 5, 3] 8,7,5,3 [8, 7, 5, 3] ),我想验证这些数字是成对的互质数。

I wonder whether it is possible to do it with two nested Arrays.stream and map methods, something like : Arrays.stream(r -> gcd(r, Map...) . 我想知道是否有可能使用两个嵌套的Arrays.streammap方法,例如: Arrays.stream(r -> gcd(r, Map...)

Can you help me? 你能帮助我吗?

Your problem reduces to how to generate all the pairs in the array. 您的问题减少到如何生成阵列中的所有对。 Then you can just use allMatch to check for the pairwise co-prime property. 然后,您可以使用allMatch来检查allMatch对共质数属性。

This would be a possible implementation: 这可能是一种实现:

private static boolean isCoPrime(int a, int b) {
    if (b == 0) return a == 1;
    return isCoPrime(b, a % b);
}

private static boolean isPairwiseCoPrime(int[] arr) {
    return IntStream.of(arr)
                    .allMatch(a -> IntStream.of(arr).filter(b -> b != a).allMatch(b -> isCoPrime(a, b)));
}

This will generate all possible pairs and checks if they are co-prime or not. 这将生成所有可能的对,并检查它们是否互质。 However this makes unnecessary computations as you are checking, for example, if the pair (8, 7) is co-prime and then the pair (7, 8). 但是,这在进行检查时会产生不必要的计算,例如,检查对(8,7)是否是互质的,然后检查对(7,8)。 So another workaround would be this: 因此,另一个解决方法是:

private static boolean isPairwiseCoPrime(int[] arr) {
    return IntStream.range(0, arr.length - 1)
                    .allMatch(i -> IntStream.range(i + 1, arr.length).allMatch(j -> isCoPrime(arr[i], arr[j])));
}

which is basically the pre-Java 8 translation of: 这基本上是Java 8之前的版本:

private static boolean isPairwiseCoPrime(int[] arr) {
    for(int i = 0; i < arr.length-1; i++) {
        for(int j = i + 1; j < arr.length; j++) {
             if(!isCoPrime(arr[i], arr[j])) {
                 return false;
             }
        }
    }
    return true;
}

Just as a note, as I explained in this answer , the Stream approach is not a substitution for everything, sometimes it's cleaner and shorter to use the traditional loop approach. 就像我在此答案中解释的一样,Stream方法不能替代一切,有时使用传统的循环方法更干净,更短。

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

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