可以把集合/数组转化成Stream流,使用流中的方法操作集合/数组
Stream流:先建立流式模型,再根据模型操作数据(就像一条生产线,先把流水线做好,再把商品放上去)
获取流
//1.把Collection集合转换成Stream流
private static void first(){
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();
}
//2.把数组转换成Stream流
private static void second(){
Stream<String> stream1 = Stream.of("a","b","c","d","e"); //参数也可以是一个数组,可变参数底层就是一个数组
Stream<Integer> stream2 = Stream.of(1,2,3,4,5); //数组的数据类型必须使用包装类,不能使用基本类型
}
常用方法
forEach
/*
void forEach(Consumer<? super T> action);
Consumer接口中的抽象方法void accept(T t);
Consumer是一个函数式接口,可以用lambda表达式重写
在流使用完之后数据转到下一步去了,上一步的流关闭了,不能再使用
stream.forEach使用完之后再调用就会报错
*/
/*
forEach源码:
forEach(Conumer<? super T> action){
for(String s:ls){ //ls是流,Stream类里面有of方法来把数组转化成流
action.accept(s);
}
}
*/
Stream<String> stream = Stream.of("a","b","c","d","e");
//下面两种是一样的
//lambda方式
// stream.forEach((String s)->{
// System.out.println(s);
// });
//写成内部类方式
stream.forEach(new Consumer<String>(){
@Override
public void accept(String s) {
System.out.println(s); //a b c d e
}
});
}
filter
/*
Stream<T> filter(Predicate<? super T> predicate);
Predicate接口中的抽象方法boolean test(T t);
Predicate是一个函数式接口,可以用lambda表达式重写
*/
Stream<String> stream = Stream.of("a","aa","b","c","d","e");
Stream<String> stream1 = stream.filter((String s)->{
return s.contains("a");
});
//函数式编程
stream1.forEach(System.out::println);
其他方法
//map
Stream<String> stream = Stream.of("1","2","3","4");
Stream<Integer> stream1 = stream.map((String s)->{ //将Stream数据流类型转换成另一种数据类型的Stream流
return Integer.parseInt(s);
});
//collect
Stream<String> stream = Stream.of("1","2","3","4");
List<String> list = stream .collect(Collectors.toList());//转化成list集合
//toSet类似
//toArray()转换成数组
//count
Stream<String> stream = Stream.of("a","aa","b","c","d","e");
System.out.println(stream.count()); //获取个数
//limit
Stream<String> stream = Stream.of("a","aa","b","c","d","e");
Stream<String> stream1 = stream .limit(3);//获取前3个元素,返回一个新的Stream流
//skip
Stream<String> stream = Stream.of("a","aa","b","c","d","e");
Stream<String> stream1 = stream .skip(3);//跳过前3个元素,返回一个包含剩下的元素的新的Stream流
//concat
//合并流