????????集合與數(shù)組互相轉(zhuǎn)換在日常業(yè)務(wù)開發(fā)中必不可少,有時業(yè)務(wù)需要的是集合,而程序提供的是數(shù)組;或者業(yè)務(wù)需要的是數(shù)組,而程序提供的是集合,這就需要轉(zhuǎn)換了。
以下簡單提供幾種常用的方法(以Int作為泛型示例),記錄一下方便查閱!
一、數(shù)組轉(zhuǎn)集合(2種方式)
推薦方式一文章來源:http://www.zghlxwxcb.cn/news/detail-508587.html
Integer[] arr = {2,4,6,8,10};
//方式一:最常用轉(zhuǎn)換(推薦)
List<Integer> list1 = Arrays.asList(arr);
//方式二:使用stream轉(zhuǎn)換
List<Integer> list2 = Arrays.stream(arr).collect(Collectors.toList());
二、集合轉(zhuǎn)數(shù)組(3種方式)
推薦方式一文章來源地址http://www.zghlxwxcb.cn/news/detail-508587.html
List<Integer> lst = new ArrayList<>();
lst.add(1);
lst.add(3);
lst.add(5);
lst.add(7);
lst.add(9);
//方式一:指定數(shù)組長度轉(zhuǎn)換(推薦)
Integer[] array1 = lst.toArray(new Integer[lst.size()]);
//方式二:不指定數(shù)組長度轉(zhuǎn)換
Integer[] array2 = lst.toArray(new Integer[]{});
//方式三:使用stream轉(zhuǎn)換
Integer[] array3 = lst.stream().toArray(Integer[]::new);
到了這里,關(guān)于Java集合與數(shù)組互相轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!