Conversion between list set and array in JAVA
- 2020-04-01 02:17:52
- OfStack
JAVA list,set, array between the conversion, mainly using Apache Jakarta Commons Collections, the specific method is as follows:
The import org.apache.com mons. 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 simple and simply loops through the Collection's add() method.
If you just want to convert the array to a List, you can use the java.util.arrays class in the JDK:
Import the Java. Util. Arrays;
String[] strArray = {"aaa", "BBB "," CCC "};
The List strList = Arrays. AsList (strArray);
However, the arrays.aslist () method returns a List that cannot add objects, because the implementation of this method USES the size of the array referenced by the argument to new an ArrayList.
u Collection to array
Directly use the toArray() method of the Collection, which has two overloaded versions:
Object [] toArray ();
T [] toArray (T [] a);
Taken the Map Collection
Use the Map's values() method directly.
u List and Set transformations
List List = new ArrayList(new Hashset()); / / Fixed - the size of the list
List the List = Arrays. AsList (array); / / Growable
List list = new LinkedList(arrays.aslist (array)); / / Duplicate elements are discarded
Set Set = new HashSet(arrays.aslist (array));