This is the second solution to count whether any of the number in an array repeated twice or thrice from the same array of integers using Collections class.
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class NumOfPairsAndTriplets {
public static void main(String[] args) {
//To count the number of pairs and triplets in an array of integers.
int [] numArray= {91,43,54,91,36,91,14,43,17,28,36,54,43};
int numberOfPairs=0,numberOfTriplets=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("]");
//Converting the array of integers to ArrayList using Arrays class
List<Integer> arrIntList=Arrays.stream(numArray).boxed().collect(Collectors.toList());
Set<Integer> uniqueInts=new HashSet<Integer>(arrIntList);
//Use the Collections class to check frequency of any of ArrayList integers is to 2 or 3
for (int numInt: uniqueInts) {
if (Collections.frequency(arrIntList,numInt)==2) {
numberOfPairs++;
}
if (Collections.frequency(arrIntList,numInt)==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
[ 91 43 54 91 36 91 14 43 17 28 36 54 43 ]
Total number of Pairs, available in the given array are = 2
Total number of Triplets, available in the given array are = 2

Leave a comment