Java集合间的相互转换

下面代码演示了List<-->数组、List<-->Set、数组<-->Set、Map将键转化为Set、Map将值转化为Set、Map将值转化为List等集合常用转化操作。

 

 

Java代码 复制代码 收藏代码
  1. publicclass TestApp { 
  2.  
  3.     publicstaticvoid main(String[] args) { 
  4.         //List-->数组 
  5.         List<String> list = new ArrayList<String>(); 
  6.         list.add("蹇伟"); 
  7.         list.add("Jerval"); 
  8.         list.add("杰威"); 
  9.         Object[] objects = list.toArray();//返回Object数组 
  10.         System.out.println("objects:"+Arrays.toString(objects)); 
  11.         String[] strings1 = new String[list.size()]; 
  12.         list.toArray(strings1);//将转化后的数组放入已经创建好的对象中 
  13.         System.out.println("strings1:"+Arrays.toString(strings1)); 
  14.         String[] strings2 = list.toArray(new String[0]);//将转化后的数组赋给新对象 
  15.         System.out.println("strings2:"+Arrays.toString(strings2)); 
  16.         //数组-->List 
  17.         String[] ss = {"JJ","KK"}; 
  18.         List<String> list1 = Arrays.asList(ss); 
  19.         List<String> list2 = Arrays.asList("AAA","BBB"); 
  20.         System.out.println(list1); 
  21.         System.out.println(list2); 
  22.         //List-->Set 
  23.         List<String> list3 = new ArrayList<String>(new HashSet<String>());  
  24.         //Set-->List 
  25.         Set<String> set = new HashSet<String>(new ArrayList<String>()); 
  26.         //数组-->Set 
  27.         String[] strs = {"AA","BB"}; 
  28.         Set<String> set2 = new HashSet<String>(Arrays.asList(strs)); 
  29.         System.out.println(set2); 
  30.         //Set-->数组 
  31.         Set<String> set3 = new HashSet<String>(Arrays.asList("PP","OO")); 
  32.         String[] strSet = new String[set3.size()]; 
  33.         set3.toArray(strSet); 
  34.         System.out.println(Arrays.toString(strSet)); 
  35.         //Map操作 
  36.         Map<String, String> map = new HashMap<String, String>(); 
  37.         map.put("YYY", "UUU"); 
  38.         map.put("RRR", "TTT"); 
  39.         // 将键转化为Set   
  40.         Set<String> mapKeySet = map.keySet(); 
  41.         // 将值转化为Set   
  42.         Set<String> mapValuesSet = new HashSet<String>(map.values()); 
  43.         // 将值转化为List   
  44.         List<String> mapValuesList = new ArrayList<String>(map.values()); 
  45.  
  46.     } 
posted @ 2012-08-17 08:32  ajiaju  阅读(276)  评论(0编辑  收藏  举报