List、Set、Array之间相互转换


List、Set之间的转换

 

        // 数据准备
        List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("1");
        list.add("2");
        list.add("2");
        list.add("2");
        list.add("3");
        list.forEach(System.out::print); // 遍历打印 1 1 2 2 2 3 
-----------------------------------------------------------------------------------
        // List --> Set
        Set<String> set = new HashSet<String>(list);
        set.forEach(System.out::print); // 遍历打印 1 2 3
-----------------------------------------------------------------------------------
        // Set --> List
        List<String> list2 = new ArrayList<String>(set);
        list2.forEach(System.out::print); // 遍历打印 1 2 3
-----------------------------------------------------------------------------------

List、Array之间的转换

 

        // 数据准备
        String[] sourceData = new String[] {"a", "b", "b", "c", "c"};
-----------------------------------------------------------------------------------
        // Array --> List
        List<String> list = Arrays.asList(sourceData);
        list.forEach(System.out::print); // 遍历打印 a b b c c
-----------------------------------------------------------------------------------
        // List -- > Array
        Object[] array = list.toArray();
        for (Object object : array) {
            System.out.print(object); // 遍历打印 a b b c c
        }
-----------------------------------------------------------------------------------
        // 注意:由于数组有固定大小,转换为List后其大小已指定,不能对再对list进行add、remove操作
        // 错误示例
        // list.add("d"); 运行将报错:java.lang.UnsupportedOperationException

Set、Array之间的转换

 

        // 数据准备
        String[] sourceData = new String[] {"a", "b", "c", "c"};
        for (String array : sourceData) {
            System.out.print(array); // 遍历打印 a b c c
        }
-----------------------------------------------------------------------------------
        // Array --> Set(本质:list转set)
        Set<String> set2 = new HashSet<String>(Arrays.asList(sourceData));
        set2.forEach(System.out::print); // 遍历打印(去重) a b c
-----------------------------------------------------------------------------------
        // Set --> Array
        Object[] array = set2.toArray();
        for (Object object : array) {
            System.out.print(object); // 遍历打印 a b c
        }

 

0

评论0

请先

没有账号? 注册  忘记密码?