1 ) String Array.
Ex : String nameArray = {“Ram”,”Shyam”,”Mohan”,”Sohan”,”Ram”,”Shyam”,”Mohan”};
2 ) ArraList.
Ex : [“Ram”,”Shyam”,”Mohan”,”Sohan”,”Ram”,”Shyam”,”Mohan”]
As we know the Set collection having the feature to allow the store unique value. Based on that we have follow two step here to removing the duplicate from string array-
Step 1) Convert the String Array into List (ArrayList).
Arrays.asList(nameArray )
The asList() method convert your string array into List.
Step 2) Add this List (ArrayList) into Set (HashSet).
Set set = new HashSet(Arrays.asList(nameArray ));
Program:
The output of this program is :
Output: [Shohan, Mohan, Shyam, Ram]
Note: We are using HashSet so the order is not the same in which we have added the element. If you want to preserve the insertion order choose LinkedHashSet instead of HashSet.
The output of this program is :
Output: [Ram, Shyam, Mohan, Shohan]
Ex : String nameArray = {“Ram”,”Shyam”,”Mohan”,”Sohan”,”Ram”,”Shyam”,”Mohan”};
2 ) ArraList.
Ex : [“Ram”,”Shyam”,”Mohan”,”Sohan”,”Ram”,”Shyam”,”Mohan”]
As we know the Set collection having the feature to allow the store unique value. Based on that we have follow two step here to removing the duplicate from string array-
Step 1) Convert the String Array into List (ArrayList).
Arrays.asList(nameArray )
The asList() method convert your string array into List.
Step 2) Add this List (ArrayList) into Set (HashSet).
Set set = new HashSet(Arrays.asList(nameArray ));
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; class RemoveDuplicate { public static void main(String args[]) { String[] nameArray = {"Ram", "Shyam", "Mohan", "Shohan", "Ram", "Shyam","Mohan"}; Set set = new HashSet(Arrays.asList(nameArray )); System.out.println("Output: "+set); } } |
The output of this program is :
Output: [Shohan, Mohan, Shyam, Ram]
Note: We are using HashSet so the order is not the same in which we have added the element. If you want to preserve the insertion order choose LinkedHashSet instead of HashSet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; class RemoveDuplicate { public static void main(String args[]) { String[] nameArray = {"Ram", "Shyam", "Mohan", "Shohan", "Ram", "Shyam","Mohan"}; Set set = new LinkedHashSet(Arrays.asList(nameArray )); System.out.println("Output: "+set); } } |
The output of this program is :
Output: [Ram, Shyam, Mohan, Shohan]
No comments :
Post a Comment