This is the third solution to find the pairs of numbers in which their sum is divisible by 9 from an array of integers. This method uses nested IntStreams to traverse the array , add any two numbers come across in each iteration, and then uses a simple predicate to verify that the sum is divisible by 9.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Divby9PairsUsingStreams {
public static List<List<Integer>> divBy9Pairs(int[] numArr, Predicate<Integer> div9) {
System.out.println("The hardcoded array of integers given below");
Arrays.stream(numArr).forEach(x -> System.out.print(x + " "));
System.out.println("\nThe pairs of numbers which are divisible by 9");
/*
* Using the nested IntStream (2 levels), flatMap, and filter return list
* objects as pairs, the criteria is sum of each pair is divisible by 9
*/
return IntStream.range(0, numArr.length).boxed()
.flatMap(i -> IntStream.range(i + 1, numArr.length)
.filter(j -> div9.test(numArr[i] + numArr[j]))
.mapToObj(j -> Arrays.asList(numArr[i], numArr[j])))
.collect(Collectors.toList());
}
public static void main(String[] args) {
int[] intArr = { 14, 20, 7, 16, 25, 34, 4 };
System.out.println("OUTPUT:");
// Calling the function divby9 which computes the sum of pairs divisible by 9
System.out.println(divBy9Pairs(intArr, (i) -> i % 9 == 0));
}
}
OUTPUT:
OUTPUT:
The hardcoded array of integers given below
14 20 7 16 25 34 4
The pairs of numbers which are divisible by 9
[[14, 4], [20, 7], [20, 16], [20, 25], [20, 34]]

Leave a comment