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:7 | ISBN:9780136091813 | Edition: 2

Question

Write a method countCommon that accepts two lists of integers as parameters and returns the number of unique integers that occur in both lists. Use one or more sets as storage to help you solve this problem. For example, if one list contains the values (3, 7, 3, –1, 2, 3, 7, 2, 15, 15) and the other list contains the values (–5, 15, 2, –1, 7,15, 36), your method should return 4 because the elements –1, 2, 7, and 15 occur in both lists.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CountCommon {

	public static int countCommon(List<Integer> list1, List<Integer> list2) {

		int offset = 0;

		Set<Integer> set1 = new HashSet<Integer>(list1);
		Set<Integer> set2 = new HashSet<Integer>(list2);

        // this for each loop each element in set2 if it contains elemnet which alredy 
         // in set1 it will offset by one.
		for (int common : set2) {
			if (set1.contains(common))
				offset++;
		}

        // returns the offset count
		return offset;
	}

	

	public static void main(String[] args) {

		List<Integer> list = new ArrayList<Integer>();
		Collections.addAll(list, 10, 2, 12, 6, 14, 5, 16);
		List<Integer> list1 = new ArrayList<Integer>();
		Collections.addAll(list1, 2, 7, 2, 0, 12, 14, 16);

	System.out.println("Total common elements in the both lists is: " +countCommon(list,list1));
		
	}

}
Output:

Total common elements in the both lists is: 4

 

0 0

Discussions

Post the discussion to improve the above solution.