简体   繁体   中英

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.

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...) .

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.

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). 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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