Search code examples
javaarraylistlinkedhashset

Converting LinkedHashSet to ArrayList or just using ArrayList


Consider the following code:

final Set<String> allPaths = new HashSet<String>();
for (final String path: paths) {
        allPaths.add(path);
}
final MyData d = new MyData(new ArrayList<String>(allPaths));

MyData is some class I should not touch. It should get an ArrayList as an argument. Before this day, we used that way because we didn't care about the order, that is why we used Set (so there will not be duplicated). But now, I would like to keep the order of the elements, so after some research, I found out that I can use the data structure LinkedHashSet in order to do so. So I did:

final LinkedHashSet<String> allPaths = new LinkedHashSet<String>();
for (final String path: paths) {
        allPaths .add(path);
}
final MyData d = new MyData(new ArrayList<String>(allPaths));

Problem is, I'm not sure how to convert LinkedHashSet to ArrayList. Also, I thought of using ArrayList instead of LinkedHashSet so I won't have to convert it, but I'll have to iterate over the array (O(n)).

What good, clean and effiect way should I use?


Solution

  • Just use the public boolean addAll(Collection<? extends E> c) method, on the arrayList, it accepts any Collection.

    You have your LinkedHashSet:

    final LinkedHashSet<String> allPaths = new LinkedHashSet<String>();
    for (final String path: paths) {
            allPaths .add(path);
    }
    

    and then do (you can use this even if mylist is not empty):

    List<String> myList = new ArrayList<>();
    mylist.addAll(allPaths);
    

    or for even a simpler approach:

    List<String> myList = new ArrayList<>(allPaths);