如何在Java中将集合转为数组?三种方法:
1、使用toArray(new Integer[]{})方法直接转为Integer数组
2、使用toArray()方法直接转为Object数组
3、用Java8流将集合对象转换为数组的方法
下面给大家分别演示下3种转换方法的代码示例,供大家参考:
importjava.util.HashSet;importjava.util.Set;publicclassTest1{publicstaticvoidmain(String[]args){Set<Integer>allSet=newHashSet<>();allSet.add(1);allSet.add(2);allSet.add(3);allSet.add(4);allSet.add(5);allSet.add(6);printArray(toArray1(allSet));printArray(toArray2(allSet));printArray(toArray3(allSet));}privatestaticvoidprintArray(Object[]arr){for(Objecto:arr){System.out.print(o+",");}System.out.println();}//方法一:用toArray(newInteger[]{})方法直接转为Integer数组publicstaticInteger[]toArray1(Set<Integer>allSet){Integer[]arr=allSet.toArray(newInteger[]{});returnarr;}//方法二:用toArray()方法直接转为Object数组publicstaticInteger[]toArray2(Set<Integer>allSet){Object[]objArr=allSet.toArray();Integer[]intArr=newInteger[objArr.length];for(inti=0;i<objArr.length;i++){intArr[i]=(Integer)objArr[i];}returnintArr;}//方法三:用Java8流将集合对象转换为数组的方法publicstaticInteger[]toArray3(Set<Integer>allSet){Integer[]arr=allSet.stream().toArray(Integer[]::new);returnarr;}}