一、Stream流的特点
- 结合Lambda表达式的形式,简化集合、数组的操作
- 不会改变集合中的内容
- 建议使用链式编程
- 有且只能使用一次
public class Main{ public static void main(String[] args){ ArrayList<String> list = new ArrayList<>(); Collections.addAll(list, "张三", "李四", "王五"); list.stream(); } }
二、Stream流的中间方法
名称 | 功能 |
---|---|
list.stream().filter(方法) | 过滤 |
list.stream().limit(Integer) | 获取前几个元素 |
list.stream().skip(Integer) | 跳过前几个元素 |
list.stream().distinct() | 元素去重 |
static <>Stream<> concat(Stream a, Stream b) | 将a, b两个流合并为一个流 |
list.stream().map(方法) | 转换流中的数据类型 |
三、Stream流的终结方法
- forEach遍历
- collect收集
- count统计个数
- 使用完终结方法后,无法再使用其他方法,因为其终结方法为void类型,无返回值
四、collect收集方法
可以将stream流中筛选出来的数据收集到一个集合之中
收集到Set集合之中
public class Test {
public static void main(String[] args) {
Set<String> list = new HashSet<>();
Collections.addAll(list, "张三", "李四", "王五", "赵六", "小七", "老八", "李大嘴", "王殿峰", "赵六四", "张银鸽");
Set<String> set = list.stream().filter(s -> s.length() == 2).collect(Collectors.toSet());
System.out.println(set);
}
}
(难点):收集到Map集合之中
list.stream().collect(Collectors.toMap(new Function<String, String>() {
@Override
public String apply(String s) {
return null;
}
},
new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return null;
}
}
));
参数一:键的生成规则 Function 泛型一:表示流中每一个数据的类型 泛型二:表示Map集合中数据的类型 方法apply 形参:依次表示流里面的每一个数据 方法体:生成键的代码 返回值:已经生成的键 参数二:值的生成规则 Function 泛型一:表示流中每一个数据的类型 泛型二:表示Map集合中数据的类型 方法apply 形参:依次表示流里面的每一个数据 方法体:生成值的代码 返回值:已经生成的值
五、Stream的使用步骤
- 获取Stream流对象
- 使用中间方法处理数据
- 使用终结方法处理数据
六、获取Stream流对象
单列集合:Collection中默认方法stream
双列集合:不能直接采取
数组:Arrays工具类型中的静态方法stream
一堆零散的数据:Stream接口中的静态方法of