1.Write a Java program to remove duplicate elements from an arraylist without using collections (without using set)
package arrayListRemoveduplicateElements;
import java.util.ArrayList;
public class RemoveDuplicates {
public static void main(String[] args){
ArrayList<Object> al = new ArrayList<Object>();
al.add("java");
al.add('a');
al.add('b');
al.add('a');
al.add("java");
al.add(10.3);
al.add('c');
al.add(14);
al.add("java");
al.add(12);
System.out.println("Before Remove Duplicate elements:"+al);
for(int i=0;i<al.size();i++){
for(int j=i+1;j<al.size();j++){
if(al.get(i).equals(al.get(j))){
al.remove(j);
j--;
}
}
}
System.out.println("After Removing duplicate elements:"+al);
}
}
Output:
Output:
- Before Remove Duplicate elements:[java, a, b, a, java, 10.3, c, 14, java, 12]
- After Removing duplicate elements:[java, a, b, 10.3, c, 14, 12]
2. Write a Java program to remove duplicate elements from an array using Collections (Linkedhashset)
- package arrayListRemoveduplicateElements;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.List;
- public class RemoveDuplicates {
- public static void main(String[] args){
- List<String> arraylist = new ArrayList<String>();
- arraylist.add("instanceofjava");
- arraylist.add("Interview Questions");
- arraylist.add("Interview Programs");
- arraylist.add("java");
- arraylist.add("Collections Interview Questions");
- arraylist.add("instanceofjava");
- arraylist.add("Java Experience Interview Questions");
- System.out.println("Before Removing duplicate elements:"+arraylist);
- HashSet<String> hashset = new HashSet<String>();
- /* Adding ArrayList elements to the HashSet
- * in order to remove the duplicate elements and
- * to preserve the insertion order.
- */
- hashset.addAll(arraylist);
- // Removing ArrayList elements
- arraylist.clear();
- // Adding LinkedHashSet elements to the ArrayList
- arraylist.addAll(hashset );
- System.out.println("After Removing duplicate elements:"+arraylist);
- }
- }
Output:
- Before Removing duplicate elements:[instanceofjava, Interview Questions, Interview
- Programs, java, Collections Interview Questions, instanceofjava, Java Experience Interview
- Questions]
- After Removing duplicate elements:[java, Collections Interview Questions, Java Experience
- Interview Questions, Interview Questions, instanceofjava, Interview Programs]