Write a method countUnique that accepts a list of integers as a parameter and returns the number of unique integer values in the list. Use a set as auxiliary storage to help you solve this problem. For example, if a list contains the values (3, 7, 3, –1, 2, 3, 7, 2, 15, 15), your method should return 5. The empty list contains 0 unique values.
package collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CountUnique {
public static int countUnique(List<Integer> list) {
// use HashSet it will remove the duplicates if any
Set<Integer> set = new HashSet<Integer>(list);
int uniqueCount = set.size();
// get the hashset size the return the count
return uniqueCount;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, 5, 6, 2, 8, 8, 4, 5, 2, 54, 2, 5, 6);
System.out.println("total unique integers are: " +countUnique(list));
}
}
Output:
total unique integers are: 6