java集合的互轉

List<-->數組、List<-->Set、數組<-->Set、Map將鍵轉化爲Set、Map將值轉化爲Set、Map將值轉化爲List等集合常數組

 

public class Test {

    public static void main(String[] args) {
        //List-->數組
        List<String> list = new ArrayList<String>();
        list.add("Tom");
        list.add("Java");
        list.add("Jack");
        Object[] objects = list.toArray();//返回Object數組
        System.out.println("objects:"+Arrays.toString(objects));
        String[] strings1 = new String[list.size()];
        list.toArray(strings1);//將轉化後的數組放入已經建立好的對象中
        System.out.println("strings1:"+Arrays.toString(strings1));
        String[] strings2 = list.toArray(new String[0]);//將轉化後的數組賦給新對象
        System.out.println("strings2:"+Arrays.toString(strings2));
        //數組-->List
        String[] ss = {"Jack","Kitter"};
        List<String> list1 = Arrays.asList(ss);
        List<String> list2 = Arrays.asList("Tom","Jack");
        System.out.println(list1);
        System.out.println(list2);
        //Set --> List
        List<String> list3 = new ArrayList<String>(new HashSet<String>()); 
        //List --> Set
        Set<String> set = new HashSet<String>(new ArrayList<String>());
        //數組-->Set
        String[] strs = {"AA","BB"};
        Set<String> set2 = new HashSet<String>(Arrays.asList(strs));
        System.out.println(set2);
        //Set-->數組
        Set<String> set3 = new HashSet<String>(Arrays.asList("PP","OO"));
        String[] strSet = new String[set3.size()];
        set3.toArray(strSet);
        System.out.println(Arrays.toString(strSet));
        //Map操做
        Map<String, String> map = new HashMap<String, String>();
        map.put("YYY", "UUU");
        map.put("RRR", "TTT");
        // 將鍵轉化爲Set  
        Set<String> mapKeySet = map.keySet();
        // 將值轉化爲Set  
        Set<String> mapValuesSet = new HashSet<String>(map.values());
        // 將值轉化爲List  
        List<String> mapValuesList = new ArrayList<String>(map.values());

    }
}
相關文章
相關標籤/搜索