Java(基本数据类型)数组转List简述

1.Java(基本数据类型)数组转List简述
2.List转Java(基本数据类型)数组简述
3.List<String>转为String[]数组,String[]数组转为List<String>

数组转LIST:

为了方便大家copy,简单
若是包装类(Integer,Long,Double)或String等数组转list

String[] temp = new String[3];
temp[0] = “1”;
temp[1] = “2”;
temp[2] = “3”;

第一种方法: List<String> listA = Arrays.asList(temp)

这种方法数组转成的listA,不能对List增删,只能查改,否则抛异常。

使用场景:Arrays.asList(strArray)方式仅能用在将数组转换为List后,不需要增删其中的值,仅作为数据源读取使用。


第二种方法: List<String> listB = new ArrayList(Arrays.asList(temp));

通过ArrayList的构造器,将Arrays.asList(strArray)的返回值由java.util.Arrays.ArrayList转为java.util.ArrayList,支持增删改查的方式

使用场景:需要在将数组转换为List后,对List进行增删改查操作,在List的数据量不大的情况下,可以使用。


第三种方法: 1. List<String> listC = new ArrayList<>(temp.length);

2. Collections.addAll(listC,temp);

通过Collections.addAll(arrayList, strArray)方式转换,根据数组的长度创建一个长度相同的List,然后通过Collections.addAll()方法,将数组中的元素转为二进制,然后添加到List中,这是最高效的方法。

使用场景:需要在将数组转换为List后,对List进行增删改查操作,在List的数据量巨大(1W+)的情况下,优先使用,可以提高操作速度。


第四种方法: Stream的更优写法,以及boxed封装

    int[] a = new int[3];
        a[0] = 1;
        a[1] = 2;
        a[2] = 3;
   List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
       System.out.println(list);

        long[] b = new long[3];
        b[0] = 1L;
        b[1] = 2L;
        b[2] = 3L;
    List<Long> longList= Arrays.stream(b).boxed().collect(Collectors.toList());
    System.out.println(longList);

    double[] c = new double[3];
    c[0] = 1.1;
    c[1] = 21.1;
    c[2] = 31.1;
    List<Double> doubleList= Arrays.stream(c).boxed().collect(Collectors.toList());
    System.out.println(doubleList);

   String[] temp = new String[3];
        temp[0] = "1";
        temp[1] = "2";
        temp[2] = "3";
        Stream<String> stream = Arrays.stream(temp);
        List<String> list = stream.collect(Collectors.toList());
        System.out.println(list);

简而言之:

int(Integer)=>Integer: List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());

long(Long)=>Long: List<Long> list = Arrays.stream(b).boxed().collect(Collectors.toList());

double(Double)=>Double: List<Double> list = Arrays.stream(c).boxed().collect(Collectors.toList());

String=>String Arrays.stream(temp).collect(Collectors.toList())

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶孤崖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值