✅ To convert an ArrayList
to a HashSet
in one line, just use the HashSet
constructor:
Set<String> set = new HashSet<>(arrayList);
💡 Example:
List<String> arrayList = List.of("apple", "banana", "apple", "cherry");
Set<String> set = new HashSet<>(arrayList); // One-liner conversion
System.out.println(set); // Output: [banana, cherry, apple] (order not guaranteed, duplicates removed)
🧠 Notes:
- ✅ Duplicates are removed automatically.
- ❌ Order is not preserved (because
HashSet
is unordered). - If you want to preserve insertion order, you can use:
Set<String> set = new LinkedHashSet<>(arrayList);