Java 获取、创建 stream 流操作对象的几种方法
package com.zhong.streamdemo.createstreamdemo;
import java.util.*;
import java.util.stream.Stream;
public class CreateStream {
public static void main(String[] args) {
System.out.println("-------------获取 List 对象的 stream 操作对象-------------");
List<String> arrayList = new ArrayList<>(List.of("小钟", "小王", "王五", "王中王", "大小王", "张三", "李四"));
Stream<String> listStream = arrayList.stream();
listStream.forEach(System.out::println);
System.out.println("-------------获取 Set 对象的 stream 操作对象-------------");
Set<String> hashSet = new HashSet<>(List.of("小钟", "小王", "王五", "王中王", "大小王", "张三", "李四"));
Stream<String> setStream = hashSet.stream();
setStream.forEach(System.out::println);
System.out.println("-------------获取 Map 对象的 stream 操作对象-------------");
Map<String, Integer> hashMap = new HashMap<>(Map.of("小钟",1, "小王",2, "王五",3, "王中王",4, "大小王",5, "张三",6, "李四",7));
Stream<String> keyStream = hashMap.keySet().stream();
Stream<Integer> valueStream = hashMap.values().stream();
Stream<Map.Entry<String, Integer>> mapStream = hashMap.entrySet().stream();
keyStream.forEach(System.out::println);
valueStream.forEach(System.out::println);
mapStream.forEach(System.out::println);
System.out.println("-------------数组创建 stream 流-------------");
String[] names = {"小钟", "小王", "王五", "王中王", "大小王", "张三", "李四"};
Stream<String> arrStream = Arrays.stream(names);
arrStream.forEach(System.out::println);
}
}