![]() |
VOOZH | about |
In Java, ArrayList allows random access because it works like an array. It means you can access any element by its index in O(1) at any time. A TreeSet is a sorted set implementation of the Set interface based on a TreeMap. It provides log(n) time complexity for basic operations like add, remove, and contains due to its tree implementation.
In this article, we will learn how to convert an ArrayList or an Array into a TreeSet in Java.
ArrayList<Type> arrayList = (initialize and add elements to the ArrayList)
TreeSet<Type> treeSet = new TreeSet<>(arrayList);Below is the implementation to convert an ArrayList to a TreeSet.
Elements of CourseList: [C++, Java, Python, Java] Elements of CourseSet: [C++, Java, Python]
T[] array = {array elements};
// Convert array to TreeSet
TreeSet<T> treeSet = new TreeSet<>(Arrays.asList(array));
Below is the implementation to convert an Array to a TreeSet.
Elements of Course Array: [Java, Python, Python, C++] Elements of Course Set: [C++, Java, Python]