Given a list of elements of type , remove the duplicates from the list in place - Java java.util

Java examples for java.util:List Duplicate Element

Description

Given a list of elements of type , remove the duplicates from the list in place

Demo Code


//package com.java2s;

import java.util.ArrayList;

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

import java.util.Set;

public class Main {
    public static void main(String[] argv) {
        List list = java.util.Arrays.asList("asdf", "java2s.com");
        removeDuplicates(list);//from   w  w w .  java2 s .  co  m
    }

    /**
     * Given a list of elements of type <T>, remove the duplicates from the list in place
     * 
     * @param <T>
     * @param list
     */
    public static <T> void removeDuplicates(List<T> list) {
        // uses LinkedHashSet to keep the order
        Set<T> set = new LinkedHashSet<T>(list);

        list.clear();
        list.addAll(set);
        if (list instanceof ArrayList) {
            ((ArrayList<T>) list).trimToSize();
        }
    }
}

Related Tutorials