This is the first solution to count whether any of the number in an array repeated twice or thrice from the same array of integers using HashMap collection.
import java.util.HashMap;
import java.util.Map.Entry;
public class NumOfPairsAndTriplets {
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};
int numberOfPairs=0,numberOfTriplets=0;
HashMap<Integer, Integer> availablePairs=new HashMap<Integer, Integer> ();
//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);
}
//Traversing through the HashMap for checking the any of the HashMap entries value for 2 & 3
for(Entry<Integer, Integer> mapOfNums:availablePairs.entrySet()) {
if(mapOfNums.getValue()==2)
numberOfPairs++;
if(mapOfNums.getValue()==3)
numberOfTriplets++;
}
System.out.println("Total number of Pairs, available in the given array are = "+numberOfPairs);
System.out.println("Total number of Triplets, available in the given array are = "+numberOfTriplets);
}
}
Output:
The given array of integers is below
[ 1 3 4 1 6 9 4 3 7 8 3 ]
Total number of Pairs, available in the given array are = 2
Total number of Triplets, available in the given array are = 1

Leave a comment