Convert Set to List without creating new List
To convert a Set to a List in Java without creating a new List object, you can use the List constructor that takes a Collection as an argument.
To convert a Set to a List in Java, you can pass the Set to the constructor of a List implementation such as ArrayList. This creates a new, independent List object containing the same elements.
For example, given a Set called set, you can create a List using the following code:
List<String> list = new ArrayList<>(set);This creates a new ArrayList object that is initialized with a copy of the elements from the Set.
Note that this approach creates a new List object with its own internal storage. The List and the Set are independent; modifying the List will not affect the original Set, and vice versa.
Here is an example of how you can use this method to convert a Set to a List and then modify the List:
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("cherry");
List<String> list = new ArrayList<>(set);
list.add("date");
System.out.println(set); // prints elements in arbitrary order (e.g., [apple, banana, cherry])
System.out.println(list); // prints [apple, banana, cherry, date]In this example, the List contains a copy of the Set's elements. Modifying the List does not affect the original Set. Note that because HashSet does not guarantee iteration order, the order of elements in the resulting List is arbitrary.