Write a method countUnique that takes a List of integers as
Write a method countUnique that takes 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.
Solution
package arraylistexample;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class ARRAYLISTEXAMPLE {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.print(\"Enter some numbers..\");
System.out.println(\"Press any non integer(Either Float or character ) for ending the input\");
while (scanner.hasNextInt()) {
int i = scanner.nextInt();
list.add(i);
}
int k = alok.countUnique(list);
System.out.print(\" Total number of unique elements Are : \\t\" + k);
}
}
class alok {
public static int countUnique(List<Integer> lst) {
Set<Integer> set = new HashSet<>(lst);
System.out.println(\"Set values .....\");
set.stream().forEach((temp) -> {
System.out.print(temp + \"\\t\");
});
int n = set.size();
return n;
}
}
