SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Java Collections Framework
Exercise:
Exercises
Question:6 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.