目录
简单了解下流(Stream)的概念:
流(Stream)与集合类似,但集合中保存的是数据,而Stream中保存对集合或数组数据的操作。
Stream特点
• Stream 自己不会存储元素。 • Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。 • Stream 操作是延迟执行的,会等到需要结果的时候才执行。
Stream的使用步骤
创建: • 新建一个流。 中间操作: • 在一个或多个步骤中,将初始Stream转化到另一个Stream的中间操作。 终止操作: • 使用一个终止操作来产生一个结果。该操作会强制之前的延迟操作立即执行,在此之后,该Stream就不能使用了。
常见的中间操作
//创建数据集合
Collection<String> collection = new ArrayList<>();
collection.add("121");
collection.add("132");
collection.add("1234");
collection.add("1234");
collection.add("123352");
collection.add("242");
collection.add("2432");
collection.add("2432");
collection.add("24325");
collection.add("932");
collection.add("32");
collection.add("346");
1、filter(筛选)
//获取集合中长度大于3的元素
collection.stream().filter((num)->num.length()>3).forEach(System.out::println);
2、limit(限制)
//获取集合的第一页数据(前三条)
collection.stream().limit(3).forEach(System.out::println);
3、skip(跳跃)
//获取集合的第二页数据(4~6条)
collection.stream().skip(3).limit(3).forEach(System.out::println);
4、distinct(去重)
//获取集合中不重复的元素
collection.stream().distinct().forEach(System.out::println);
5、sorted(排序)
//将集合中的元素进行排序
collection.stream().sorted().forEach(System.out::println);
//将集合中的元素进行排序(按照元素的长度降序)
collection.stream().sorted(((o1, o2) -> o2.length()-o1.length())).forEach(System.out::println);
6、map(函数型接口)
//将集合中的元素转换成int类型
// 1、原版
collection.stream().map((s)->Integer.parseInt(s)).forEach(System.out::println);
// 2、简写,使用的方法引用
collection.stream().map(Integer::parseInt).forEach(System.out::println);
// 验证有没有转化为整数型
collection.stream().map(Integer::parseInt).forEach(num->{System.out.println(num+10);});
7、parallel(多线程)
//使用多线程操作集合中的元素
collection.stream().parallel().forEach(th->{System.out.println(Thread.currentThread().getName()+":"+th);});
常见的终止操作
1、foreach
// foreach为终止操作
collection.stream().forEach(System.out::println);
2、min(最小)
//获取集合中元素长度最小的元素
Optional<String > str =collection.stream().min((o1, o2) -> o1.length()-o2.length());
// 查看
System.out.println(str.get());
3、max(最大)
//获取集合中元素长度最大的元素
Optional<String > str =collection.stream().max((o1, o2) -> o1.length()-o2.length());
System.out.println(str.get());
4、count(计数)
//获取集合中长度为3的元素个数
long count = collection.stream().filter(o->o.length()==3).count();
System.out.println(count);
5、reduce(求和)
//将集合中的元素转成int类型并计算总和 这里0指初始值
Integer integer = collection.stream().map(Integer::parseInt).reduce(0,(o1,o2)->o1+o2);
System.out.println(integer);
6、collect(转换)
//将Stream流对象转换成List、Set、Map集合
List<String> list = collection.stream().collect(Collectors.toList());
System.out.println(list);
Set<String> set = collection.stream().collect(Collectors.toSet());
System.out.println(set);
// key不能重复,会报错,我直接先set后map
Map<String,Integer> map = set.stream().collect(Collectors.toMap(o->o,o->o.length()));
System.out.println(map);
数组流的引用
// 数组流的引用
public static void list_stream(){
int[] arr = {1,3,4,5,23,2};
// 实例化, 一般直接使用:即 Arrays.stream(arr).forEach(num-> System.out.println(num+10));
IntStream stream = Arrays.stream(arr);
stream.forEach(num-> System.out.println(num+10));
}