GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — java-coding-problems/IntersectionOfTwoArray.java at main · GitH05/java-coding-problems

Expand file tree

/

IntersectionOfTwoArray.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
55 lines (48 loc) · 1.75 KB
/

IntersectionOfTwoArray.java

Copy path

File metadata and controls

55 lines (48 loc) · 1.75 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class IntersectionOfTwoArray {
public static void main(String[] args) {
IntersectionOfTwoArray intersection = new IntersectionOfTwoArray();
int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 4, 5, 6, 7, 8 };
intersection.findIntersection(arr1, arr2);
intersection.IntersectionWithoutDuplicate();
}
// method to find the intersection of two arrays - 1 | duplicate may exist
public void findIntersection(int[] arr1, int[] arr2) {
System.out.print("Intersection: ");
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
System.out.print(arr1[i] + " ");
}
}
}
}
/*
* if there multiple number of same type then it will print all of them and
* their would be duplicate like
*
* int[] arr1 = {1, 2, 2, 3};
* int[] arr2 = {2, 2, 4};
*
* code would print 2 2 2 2, because each 2 in arr1 matches each 2 in arr2.
*/
// Here method to find the intersection of two arrays - 2 | avoid duplicates
public void IntersectionWithoutDuplicate() {
int[] arr1 = { 1, 2, 3, 3, 5, 7, 7 };
int[] arr2 = { 4, 2, 3, 3, 6, 7, 5 };
Set<Integer> set1 = new HashSet<>();
for (int i = 0; i < arr1.length; i++) {
set1.add(arr1[i]);
}
Set<Integer> set2 = new LinkedHashSet<>(); // maintains insertion order
for (int num : arr2) {
if (set1.contains(num)) {
set2.add(num);
}
}
System.out.println("\nIntersection without duplicates: " + set2);
}
}
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.