0

This sounds like a really dumb question, but all Google results on the first pages either:

  • Use a 3rd party library
  • Use an explicit loop
  • Return a List<Object> instead of List<YourType>
  • Answer the reversed question of converting an ArrayList to Set

What's the best way to convert a LinkedHashSet to an ArrayList while avoiding all of the above?

Albert Hendriks
  • 1,979
  • 3
  • 25
  • 45
  • 2
    Did you try `new ArrayList<>(yourSet)`? – Eran Jan 13 '20 at 10:59
  • "best way" in terms of performance or in terms of simplicity/readability? – mangusta Jan 13 '20 at 11:03
  • @mangusta if that matters for the answer I'd love to know. – Albert Hendriks Jan 13 '20 at 11:04
  • I'm not sure if "ArrayList<>(yourSet)" would be more efficient than using third-party library. It might be as bad as looping, while third-party libs could make use of internal representation of hashset to straightforwardly convert it into arraylist in constant time. So I recommend to do a bit of research – mangusta Jan 13 '20 at 11:13

2 Answers2

3

A simple call to ArrayList's constructor should do the trick:

List<MyObject> myList = new ArrayList<>(myLinkedHashSet);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("A");
set.add("B");
set.add("C");

List<String> list = new ArrayList<>(set);
System.out.println(list); // [A, B, C]
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111