Removing duplicates Elements from List

By | August 10, 2017

This program uses Java collections’ List.

First we store some elements in Java ArrayList and then store it in LinkedHashSet.

As we know that java sets have property to have unique elements only, so once we copy our List into LinkedHashSet, it removed the duplicate elements of course.

Obviously, we have many other simpler ways to perform this operation. But this is one of them.

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

public class RemoveDublicate{
    public static void main(String[] args) {
        List<String> dub = new ArrayList<String>();
        dub.add("hello");
        dub.add("World");
        dub.add("Sun");
        dub.add("hello");
        dub.add("Bike");
        System.out.println("List Before:" + dub);

        LinkedHashSet<String> Listafter = new LinkedHashSet<String>();
        Listafter.addAll(dub);
        dub.clear();
        dub.addAll(Listafter);
        System.out.println("After: " +dub);
    }
}

Output

List Before:[hello, World, Sun, hello, Bike]
After: [hello, World, Sun, Bike]