This is the third solution to find the triplets of numbers in which their sum is divisible by 9 from an array of integers. This method uses three nested IntStream to traverse array, add any three numbers come across in each iteration, and then uses 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 Divby9TripletsUsingStreams {
public static List<List<Integer>> divBy9Triplets(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 triplets of numbers which are divisible by 9");
/*
* Using the nested IntStream (3 levels), flatMap, and filter return list
* objects as triplets, the criteria is sum of each triplet is divisible by 9
*/
return IntStream.range(0, numArr.length).boxed()
.flatMap(i -> IntStream.range(i + 1, numArr.length).boxed()
.flatMap(j -> IntStream.range(j + 1, numArr.length)
.filter(k -> div9.test(numArr[i] + numArr[j] + numArr[k]))
.mapToObj(k -> Arrays.asList(numArr[i], numArr[j], numArr[k]))))
.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 triplets divisible by 9
System.out.println(divBy9Triplets(intArr, (i) -> i % 9 == 0));
}
}
OUTPUT:
OUTPUT:
The hardcoded array of integers given below
14 20 7 16 25 34 4
The triplets of numbers which are divisible by 9
[[7, 16, 4], [7, 25, 4], [7, 34, 4], [16, 25, 4], [16, 34, 4], [25, 34, 4]]

Leave a reply to MOULI Cancel reply