This is the third solution to count whether any of the number in an array repeated twice or thrice from the same array of integers using functional interface and lambda expression.
import java.util.HashMap;
public class NumberOfPairsAndTriplets {
public static void main(String[] args) {
// To count the number of pairs and triplets in an array of integers.
int[] numArray = { 1, 3, 4, 1, 6, 9, 4, 3, 7, 8, 3 };
HashMap<Integer, Integer> availablePairs = new HashMap<Integer, Integer>();
final int[] numberOfPairs = { 0 };
final int[] numberOfTriplets = { 0 };
final int[] loopCntr = { 0 };
// Display the existing array of integers
System.out.println("The given array of integers is below");
System.out.print("[ ");
for (int i = 0; i < numArray.length; i++)
System.out.print(numArray[i] + " ");
System.out.println("]");
// Create a HashMap of the given array of Integers
for (int i = 0; i < numArray.length; i++) {
if (!availablePairs.containsKey(numArray[i]))
availablePairs.put(numArray[i], 1);
else
availablePairs.put(numArray[i], availablePairs.get(numArray[i]) + 1);
}
/* Using the Lambda expression, traversing through the HashMap for checking the
* any of the HashMap entrie's value is 2 or 3 */
availablePairs.forEach((k, v) -> {
if (v == 2)
numberOfPairs[0] += 1;
if (v == 3)
numberOfTriplets[0] += 1;
loopCntr[0] += 1;
if (loopCntr[0] == availablePairs.size()) {
System.out.println("Total number of Pairs of existing number[s] from the array are " + numberOfPairs[0]);
System.out.println("Total number of Triples of existing number[s] from the array are " + numberOfTriplets[0]);
}
});
}
}
Output:
The given array of integers is below
[ 1 3 4 1 6 9 4 3 7 8 3 ]
Total number of Pairs of existing number[s] from the array are 2
Total number of Triples of existing number[s] from the array are 1

Leave a comment