Skip to content Skip to sidebar Skip to footer

Copying Linkedhashset Content To New Arraylist?

I've a listView that has some content initially. If the same content it gets, i removed the duplication through linkedhashset. Now, i want copy the linkedhashset contents i.e witho

Solution 1:

The following line just inserts all the elements into the arraylist starting from the 0th index

p.addAll(0,lhm);

And, the elements which were added using these lines were still present in the arraylist:

p.add(new Price("Banana", 60));
p.add(new Price("Apple", 80));

So, you should clear the array list before adding the items from the linkedhashset, in case you don't want the duplicates. i.e.

p.clear();
p.addAll(lhm); // and, at this point you don't need the index.

Solution 2:

See this full solution may be help you

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
publicclassLinkedHashSetToList {

        publicstaticvoidmain(String[] args) {
        Set<String> lhs = newLinkedHashSet<String>();
        lhs.add("mumbai");
        lhs.add("delhi");
        lhs.add("kolkata");
        lhs.add("chandigarh");
        lhs.add("dehradun");
        //print linkedhashset
        System.out.println("lhs is = "+lhs);
        List<String> list = newArrayList<String>(lhs);
        // print arraylist
        System.out.println("ArrayList Is = "+list);

    }

}

Output:

lhsis= [mumbai, delhi, kolkata, chandigarh, dehradun]
ArrayListIs= [mumbai, delhi, kolkata, chandigarh, dehradun]

Reference : How to Convert a LinkedHashSet to ArrayList

Solution 3:

A Set will only ensure that its own elements are unique. You can't expect ArrayList to exclude duplicates unless the entire collection is filtered through a set. For example:

...
p.addAll(0,lhm);
p = newArrayList<String>(newHashSet<String>(p));

Post a Comment for "Copying Linkedhashset Content To New Arraylist?"