We all know that ArrayList allows duplicate elements, So how can we remove these duplicate elements if we want ? we don't have any pre defined methods to satisfy our requirement. So by passing the list to set we can achieve this.Why because set does not allows us to pass duplicates.After passing the list to set , again we will pass set to list so, that we will get newly modified list without duplicates.
Let's go for Examples:-
in this examples i will use two classes HashSet and LinkedHashSet the difference b/w them is if we useHashSet doesn't maintain insertion order where as LinkedHashSet maintains insertion order like ArrayList so mostly we will use LinkedHashSet
we will see both of them in following examples.
Let's go for Examples:-
in this examples i will use two classes HashSet and LinkedHashSet the difference b/w them is if we useHashSet doesn't maintain insertion order where as LinkedHashSet maintains insertion order like ArrayList so mostly we will use LinkedHashSet
we will see both of them in following examples.
Example:-
- package com.system;
- import java.util.*;;
- public class Test{
- public static void main(String args[]){
- List al=new ArrayList();
- al.add("one");
- al.add("one");
- al.add("two");
- al.add("three");
- al.add("four");
- al.add("two");
- System.out.println("Before removing The duplicates"+al);
- //By using HashSet
- Set set= new HashSet(al);
- List al1=new ArrayList(set);
- System.out.println("Elements, after removing the duplicates"+al1);
- List al2=new ArrayList();
- al2.add("java");
- al2.add("java");
- al2.add("oracle");
- al2.add(".net");
- al2.add("SAP");
- al2.add("oracle");
- System.out.println("Before removing The duplicates"+al2);
- // By using LinkedHasSet
- Set set2= new HashSet(al2);
- List al3=new ArrayList(set2);
- System.out.println("Elements, after removing the duplicates"+al3);
- }
- }


0 comments:
Post a Comment