To convert between JAVA lists, sets, and arrays, you mainly use Apache Jakarta Commons Collections. The specific methods are as follows:
import org.apache.commons.collections.CollectionUtils;
String[] strArray = {"aaa", "bbb", "ccc"};
List strList = new ArrayList();
Set strSet = new HashSet();
CollectionUtils.addAll(strList, strArray);
CollectionUtils.addAll(strSet, strArray);
The implementation of the CollectionUtils.addAll() method is very simple, it just uses the add() method of Collection in a loop.
If you just want to convert an array into a List, you can use the java.util.Arrays class in the JDK:
import java.util.Arrays;
String[] strArray = {"aaa", "bbb", "ccc"};
List strList = Arrays.asList(strArray);
However, the List returned by the Arrays.asList() method cannot add objects, because the implementation of this method uses the size of the array referenced by the parameter to create a new ArrayList.
★ Collection to array
Use Collection's toArray() method directly, which has two overloaded versions:
Object[] toArray();
T[] toArray(T[] a);
★ Map to Collection
Use Map's values() method directly.
★ List and Set conversion
List list = new ArrayList(new Hashset());// Fixed-size list
List list = Arrays.asList(array);//Growable
list list = new LinkedList(Arrays.asList(array));//Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));