Mhanaz Syed
Mhanaz Syed

Reputation: 269

how to remove duplicate Element from Arraylist in java

    { "744101", "744101","744101", "744102",744102","744102","744102","744102","744103","744103"}
      List<String> list2=new new ArrayList<String>();  //
           Arrays.sort(iArr);
                            for(int k=0;k<iArr.length;k++) {
                                list2.add(String.valueOf(iArr[k]));
                            }

   List li2 = new Array List(new HashSet(list2)); 

I'm unable to get result while trying to Sort Array list. Please correct me.

Upvotes: 1

Views: 3207

Answers (3)

Vilius
Vilius

Reputation: 77

As Eran mentioned, you current implementation "shuffles" the list due to HashSet implementation being used, as this Set implementation doesn't retain the order. Try using LinkedHashSet instead. As mentioned in javadoc it avoids overheads related to TreeSet. Code would be something like this

 String[] arrayToProcess = { "744101", "744101","744101", "744102","744102","744102","744102","744102","744103","744103"};

 //creates array and sorts the list
 List<String> sortedList = Arrays.asList(arrayToProcess);
 Collections.sort(sortedList);

 //removes duplicates the list, while retaining order of sorted list
 Set<String> uniqueNumbers = new LinkedHashSet<String>();
 uniqueNumbers.addAll(sortedList);

Note the implementation of Set being used is LinkedHashSet. Also this snippet makes two copies of the array so if array size is huge, I wouldn't suggest using it.

I would suggest you look up the implementations of collections in java. Because each of them has their own strengths and weaknesses:

Upvotes: 0

someone_somewhere
someone_somewhere

Reputation: 811

The TreeSet both sorts the elements and removes the duplicates.

    String[] array = { "744101", "744101","744101", "744102","744102","744102","744102","744102","744103","744103"};
    List<String> list = new ArrayList<>(new TreeSet<>(Arrays.asList(array)));

    list.forEach((element)->{
        System.out.println(element);
    });

Upvotes: 2

Filip V
Filip V

Reputation: 435

Try this:

   List<String> list = new ArrayList<>();
    Set<String> set = new HashSet<>();
    hash.addAll(list);
    list.clear();
    list.addAll(hash);

And than sort list if you want.

Upvotes: 0

Related Questions