List、Set、數組之間的轉換

 ★ 數組轉Collectionjava

使用Apache Jakarta Commons Collections:apache

 
  1. import org.apache.commons.collections.CollectionUtils;   
  2.   
  3. String[] strArray = {"aaa""bbb""ccc"};   
  4. List strList = new ArrayList();   
  5. Set strSet = new HashSet();   
  6. CollectionUtils.addAll(strList, strArray);   
  7. CollectionUtils.addAll(strSet, strArray);  

CollectionUtils.addAll()方法的實現很簡單,只是循環使用了Collection的add()方法而已。數組

若是隻是想將數組轉換成List,能夠用JDK中的java.util.Arrays類:ide

 
  1. import java.util.Arrays;   
  2.   
  3. String[] strArray = {"aaa""bbb""ccc"};   
  4. List strList = Arrays.asList(strArray);  

不過Arrays.asList()方法返回的List不能add對象,由於該方法的實現是使用參數引用的數組的大小來new的一個ArrayList。spa

 

★ Collection轉數組對象

直接使用Collection的toArray()方法,該方法有兩個重載版本:element

  1. Object[] toArray();   
  2.   
  3. T[] toArray(T[] a);  

 

★ Map轉Collectionstring

直接使用Map的values()方法。it

 

★ List和Set轉換io

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));

相關文章
相關標籤/搜索