本篇文章用于记录自己对于Stream流的学习,把经常使用的api给记录下
Stream流的三个特性
- Stream流不是一种数据结构,不保存数据,它只是在原数据集上定义了一组操作。
- 这些操作是惰性的,即每当访问到流中的一个元素,才会在此元素上执行这一系列操作。
- Stream不保存数据,故每个Stream流只能使用一次。
流的继承关系
流的使用
1、boxed,可以把基本数据类型转为Object类
/**
* @author MZ-LI
* @title: Boxed
* @projectName lambda
* @description: TODO
* @date 2021/9/23下午5:32
*/
public class BoxedDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 5);
IntStream intStream = numbers.stream().mapToInt(i -> i); //转成IntStream,这里是不能直接转为集合的,所以需要boxed方法
Stream<Integer> boxed = intStream.boxed(); //转成Stream<Integer>
}
}
2、filter过滤器(过滤不符合条件的元素)
/**
* @author MZ-LI
* @title: FilterDemo
* @projectName lambda
* @description: TODO
* @date 2021/9/23下午5:17
*/
public class FilterDemo {
public static void main(String[] args) {
Arrays.asList(1, 2, 4, 5, 10, 11).stream().filter(a -> a < 10).forEach(System.out::println);
}
}
3、map,遍历和操作流中元素
/**
* @author MZ-LI
* @title: MapDemo
* @projectName lambda
* @description: TODO
* @date 2021/9/23下午5:20
*/
public class MapDemo {
public static void main(String[] args) {
Arrays.asList("a", "b", "c").stream().map(a -> a.toUpperCase(Locale.ROOT)).forEach(System.out::printf);
System.out.println();
Arrays.asList(1, 2, 3, 4, 5).stream().map(a -> "A" + a).forEach(System.out::printf);
}
}
4、 forEach方法,遍历流元素
/**
* @author MZ-LI
* @title: ForEachDemo
* @projectName lambda
* @description: TODO
* @date 2021/9/23下午5:24
*/
public class ForEachDemo {
public static void main(String[] args) {
Arrays.asList(1, 2, 3, 4, 5).stream().forEach(System.out::print);
System.out.println();
//这里并发流条件下会失序
Arrays.asList("1", "2", "3", "4").parallelStream().forEachOrdered(System.out::printf);
System.out.println();
//多线程下仍然有序
Arrays.asList("1", "2", "3", "4").parallelStream().forEach(System.out::printf);
}
}
5、mapToInt、mapToLong、mapToDouble ,与map相似,返回对应的int、long、double类型的stream
public static void main(String[] args) {
Arrays.asList("1", "2", "3", "4").stream().mapToInt(Integer::parseInt).forEach(System.out::print);
System.out.println();
Arrays.asList("1", "2", "3", "4")