欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java list和数组的相互转换

程序员文章站 2022-04-15 18:36:03
/** * 不推荐,添加时会报错 */ @Test public void arrry2List1() { //arrry to list String [] array = new String [10000]; for (int i = 10000; i > 0; i--) { array[i] = String.valueOf(Math.round(10000)); ......
    /**
     * 不推荐,添加时会报错
     */
    @Test
    public void arrry2List1() {
        //arrry to list
        String [] array = new String [10000];
        for (int i = 10000; i > 0; i--) {
            array[i] = String.valueOf(Math.round(10000));
        }
        List<String> list = Arrays.asList(array);
        list.add("d");//UnsupportedOperationException异常
        System.out.println(list);
    }

    /**
     * 第一种方式最快一般用第一种方式
     */
    @Test
    public void arrry2List2() {
        //arrry to list
        String [] array = new String [1000000];
        for (int i = 0; i < 1000000; i++) {
            array[i] = String.valueOf(Math.round(1000000));
        }
        //new ArrayList<>(Arrays.asList(array)
        long start = System.currentTimeMillis();
        List<String> list = new ArrayList<>(Arrays.asList(array));
        System.out.println("耗时:" + (System.currentTimeMillis() - start));

        //Collections.addAll(list2,array);
        start = System.currentTimeMillis();
        List<String> list2 = new ArrayList<>(array.length);
        Collections.addAll(list2,array);
        System.out.println("耗时:" + (System.currentTimeMillis() - start));

        //stream 1
        start = System.currentTimeMillis();
        List<String> list3 = Stream.of(array).collect(Collectors.toList());
        System.out.println("耗时:" + (System.currentTimeMillis() - start));

        //stream 2
        start = System.currentTimeMillis();
        List<String> list4 = Arrays.stream(array).collect(Collectors.toList());
        System.out.println("耗时:" + (System.currentTimeMillis() - start));

        //    耗时:4
        //    耗时:8
        //    耗时:51
        //    耗时:11
    }

    /**
     * 第一种方式最快一般用第一种方式
     */
    @Test
    public void list2Arrry() {
        //arrry to list
        List<String> list = new ArrayList<>(1000000);
        for (int i = 0; i < 1000000; i++) {
            list.add(String.valueOf(Math.round(1000000)));
        }
        //new ArrayList<>(Arrays.asList(array)
        long start = System.currentTimeMillis();
        String[] array = new String[list.size()];
        String[] strings = list.toArray(array);
        System.out.println("耗时:" + (System.currentTimeMillis() - start));


        //stream 1
        start = System.currentTimeMillis();
        String[] strings1 = list.stream().toArray(String[]::new);
        System.out.println("耗时:" + (System.currentTimeMillis() - start));

//        耗时:8
//        耗时:51
    }

尽量不使用stream,原始转换速度更快

本文地址:https://blog.csdn.net/cyy356/article/details/110235600

相关标签: JAVA