What I prepared and what I got!
1. There are two lists, one has 50 numbers and the other has 75 numbers. Write code in Java to find the common elements of these two lists.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;public class CommonElements {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
// Add more numbers to list1
for (int i = 4; i <= 50; i++) {
list1.add(i);
}
List<Integer> list2 = new ArrayList<>();
list2.add(2);
list2.add(3);
list2.add(4);
// Add more numbers to list2
for (int i = 5; i <= 75; i++) {
list2.add(i);
}
List<Integer> commonElements = findCommonElements(list1, list2);
System.out.println("Common elements: " + commonElements);
}
public static List<Integer> findCommonElements(List<Integer> list1, List<Integer> list2) {
Set<Integer> set = new HashSet<>(list1);
set.retainAll(list2);
return new ArrayList<>(set);
}
}
In this example, findCommonElements
This method takes two lists as input: HashSet
To find commonalities efficiently retainAll
Method HashSet
Change it to include only the elements common to the two lists. Finally, the common elements are List
It’s easy to print.
- Importing required classes: Import
ArrayList
,HashSet
,List
andSet
Use these data structures: - Main Method:
- Create two lists.
list1
andlist2
. - Adding some numbers
list1
andlist2
. - For demonstration purposes, we added a loop:
list1
Numbers 1 to 50list2
A number between 2 and 75.
3. Find common ground:
- of
findCommonElements
The method isHashSet
fromlist1
. - next,
retainAll
Keep only contained elementslist2
. - Finally, we convert the set to a list and return it.
4. Printing common elements: Common elements are printed to the console.
This code is straightforward: retainAll
An efficient and straightforward way to find the intersection of two sets.