给定一个Stream, 任务是将该流转换为Java 8中的ArrayList。
例子:
Input: Stream: [1, 2, 3, 4, 5]
Output: ArrayList: [1, 2, 3, 4, 5]Input: Stream: ['G', 'e', 'e', 'k', 's']
Output: ArrayList: ['G', 'e', 'e', 'k', 's']
使用Collectors.toList()方法:
- 获取要转换的流。
- 使用collect()和Collectors.toList()方法将流收集为List。
- 将此列表转换为ArrayList
- 返回/打印ArrayList
程序:
//Java program to convert Stream to ArrayList
//using Collectors.toList() methodimport java.util.*;
import java.util.stream.*;
public class GFG {//Function to get ArrayList from Stream
public static <
T>
ArrayList<
T>
getArrayListFromStream(Stream<
T>
stream)
{//Convert the Stream to List
List<
T>
list = stream.collect(Collectors.toList());
//Create an ArrayList of the List
ArrayList<
T>
arrayList = new ArrayList<
T>
(list);
//Return the ArrayList
return arrayList;
}//Driver code
public static void main(String args[])
{Stream<
Integer>
stream = Stream.of( 1 , 2 , 3 , 4 , 5 );
//Convert Stream to ArrayList in Java
ArrayList<
Integer>
arrayList = getArrayListFromStream(stream);
//Print the arraylist
System.out.println( "ArrayList: " + arrayList);
}
}
输出如下:
ArrayList: [1, 2, 3, 4, 5]
使用Collectors.toCollection()方法:
方法:
- 获取要转换的流。
- 使用collect()和Collectors.toCollection()方法将流收集为ArrayList。
- 返回/打印ArrayList
程序:
//Java program to convert Stream to ArrayList
//using Collectors.toList() methodimport java.util.*;
import java.util.stream.*;
public class GFG {//Function to get ArrayList from Stream
public static <
T>
ArrayList<
T>
getArrayListFromStream(Stream<
T>
stream)
{//Convert the Stream to ArrayList
ArrayList<
T>
arrayList = stream
.collect(Collectors
.toCollection(ArrayList:: new ));
//Return the ArrayList
return arrayList;
}//Driver code
public static void main(String args[])
{Stream<
Integer>
stream = Stream.of( 1 , 2 , 3 , 4 , 5 );
//Convert Stream to ArrayList in Java
ArrayList<
Integer>
arrayList = getArrayListFromStream(stream);
//Print the arraylist
System.out.println( "ArrayList: "
+ arrayList);
}
}
【如何在Java 8中从Stream获取ArrayList()】输出如下:
ArrayList: [1, 2, 3, 4, 5]
推荐阅读
- 如何从PHP中的路径获取文件名()
- 如何获得数据科学实习()
- LINUX下载编译FreeSwitch
- Harbor企业级镜像仓库安装部署
- Docker-compose搭建nginx负载均衡
- LINUX下载编译ldns
- jenkins安装与配置
- TCP长连接实践与挑战
- 搏动"城市之肾",可视化突破海绵城市发展困境