Java.Collections.How to convert a HashSet to an ArrayList in one line?

✅ One-liner:

List<String> list = new ArrayList<>(hashSet);

💡 Example:

Set<String> hashSet = Set.of("apple", "banana", "cherry");

List<String> list = new ArrayList<>(hashSet); // One-liner conversion

System.out.println(list); // Output: [apple, banana, cherry] (order not guaranteed)

🧠 Notes:

  • This copies all elements from the HashSet to a new ArrayList.
  • The order is not preserved, because HashSet doesn’t maintain insertion order.
  • If you want to preserve insertion order, and you’re starting with a LinkedHashSet, the same one-liner works just fine.
This entry was posted in Без рубрики. Bookmark the permalink.