java8新特性stream操作

2019-08-21  本文已影响0人  南_4231

目录结构

1、流的概念

2、流的类型

3、流的基本用法

一、流的概念


摘自菜鸟教程

二、流的类型

流的类型

三、流的基本用法

例子中用到的测试数据:

list:

测试数据-list

list1:

测试数据-list1

1、原始流Stream的用法

原始流Stream的用法

(1)forEach

作用:遍历流中的每个数据

System.out.println("stream遍历结果:");
list.stream().forEach(item -> System.out.println(item));

输出结果:

forEach遍历流中的每个数据

(2)map

作用:映射每个元素到对应的结果

List addOneList = list.stream().map(i -> i +"1").distinct().collect(Collectors.toList());
System.out.println("每个元素都拼接'1'的结果:" + JSON.toJSONString(addOneList));

输出结果:

map映射每个元素到对应的结果

(3)limit

作用:获取指定数量的流

List limitList = list.stream().limit(3).collect(Collectors.toList());
System.out.println("获取指定数量的流的结果:" + JSON.toJSONString(limitList));

输出结果:

limit获取指定数量的流

(4)sort

作用:对流进行排序

排序步骤:

A、先要将排序列表中的实体实现Comparable接口,并重写compareTo方法。要按哪个字段排序,重写compareTo方法时就处理哪个字段

sort对流进行排序

B、使用sort()方法进行排序

/*********************** 未排序的结果 *************************/
System.out.println("未排序的结果:");
System.out.println(JSON.toJSONString(list1));
/*********************** 按岁数升序排序的结果 *************************/
List sortedList = list1.stream().sorted(Comparator.comparing(TestUser::getAge)).collect(Collectors.toList());
System.out.println("按岁数升序排序的结果-stream.sort方式:");
System.out.println(JSON.toJSONString(sortedList));
/*********************** 按岁数降序排序的结果 *************************/
List reverseSortedList = list1.stream().sorted(Comparator.comparing(TestUser::getAge).reversed()).collect(Collectors.toList());
System.out.println("按岁数降序排序的结果-stream.sort方式:");
System.out.println(JSON.toJSONString(reverseSortedList));

输出结果:

使用stream().sort()方法进行排序

Collections.sort()与stream().sort()排序的异同
相同之处:
Collections.sort()方法同样都要先将排序列表中的实体实现Comparable接口,并重写compareTo方法
不同之处:
对于相同的compareTo逻辑,stream().sort()方式与Collections.sort()方式顺序相反

/*********************** 按岁数降序排序的结果 *************************/
Collections.sort(list1);
System.out.println("按岁数降序排序的结果-Collections.sort方式:");
System.out.println(JSON.toJSONString(list1));
//Collections.reverse()方法可以将当前的列表倒序排列
Collections.reverse(list1);
/*********************** 按岁数升序排序的结果 *************************/
System.out.println("按岁数升序排序的结果-Collections.sort方式:");
System.out.println(JSON.toJSONString(list1));

输出结果:

使用Collections.sort()方法进行排序

(5)filter

作用:通过设置的条件过滤出元素,注意:满足条件的会被保留(与Collection.removeIf()方法相反)

Stream stream1 = list1.stream().filter(item ->"wangwu".equals(item.getName()));
List filterList = stream1.collect(Collectors.toList());
System.out.println("filter过滤后的结果:" + JSON.toJSONString(filterList));
filter通过设置的条件过滤出元素

注意:stream().filter()与Collection.removeIf()方法的区别

filter:满足条件的会被保留

removeIf:满足条件的会被去掉

list1.removeIf(item -> "wangwu".equals(item.getName()));
System.out.println("removeIf过滤后的结果:" + JSON.toJSONString(list1));

输出结果:

removeIf通过设置的条件过滤出元素
上一篇 下一篇

猜你喜欢

热点阅读