-
Notifications
You must be signed in to change notification settings - Fork 0
/
Java-Removing_Duplicate-elements_from_array.txt
93 lines (70 loc) · 2.37 KB
/
Java-Removing_Duplicate-elements_from_array.txt
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//IDENTIFY UNIQUE ELEMENTS FROM A GIVEN ARRAY
//APPROACH 1 - USING ARRAYLIST (WITH CONTAINS MATHOD)
import java.util.*;
public class RemoveDuplicate{
public static ArrayList<Integer> unique(ArrayList<Integer> list){
ArrayList<Integer> al = new ArrayList<Integer>();
for(Integer l:list){
if(!al.contains(l)){
al.add(l);
}
}
return al;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the digit for size of array");
int size = sc.nextInt();
System.out.println("size of array :- "+size);
Integer[] arr= new Integer[size];
for(int i =0; i<arr.length; i++){
arr[i] =sc.nextInt();
}
System.out.print("Array Entered is:- ");
for(int j = 0; j < arr.length; j++) {
System.out.print(arr[j]+" ");}
ArrayList<Integer> list= new ArrayList<Integer>(Arrays.asList(arr));
System.out.println();
System.out.println("ArrayList with duplicates: "+ list);
ArrayList<Integer> alInt = unique(list);
System.out.println("ArrayList of Unique Elements:- "+alInt);
}
}
INPUTS:- 5 // ARRAY SIZE
2 // ARRAY ELEMENTS
1
3
2
3
OUTPUT:-
Enter the digit for size of array
size of array :- 5
Array Entered is:- 2 1 3 2 3
ArrayList with duplicates: [2, 1, 3, 2, 3]
ArrayList of Unique Elements:- [2, 1, 3]
//APPROACH 2 - USING LinkedHashSet for identifying unique elements in a given ArrayList\
//Set internaly implements HashMap and this makes Set to contain unique elements only
import java.util.*;
public class RemoveDuplicate{
public static ArrayList<Integer> unique(ArrayList<Integer> list){
/*ArrayList<Integer> al = new ArrayList<Integer>();
for(Integer l:list){
if(!al.contains(l)){
al.add(l);
}
}*/
Set<Integer> hs = new LinkedHashSet<Integer>();
hs.addAll(list);
list.clear();
list.addAll(hs);
return list;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the digit for size of array");
int size = sc.nextInt();
.
.
...
}
}