Java版本現在已經發布到JDK13了,目前公司還是用的JDK8,還是有必要了解一些JDK8的新特性的,例如優雅判空的Optional類,操作集合的Stream流,函數式編程等等;這里就按操作例舉一些常用的Stream流操作;
Stream流簡介
A sequence of elements supporting sequential and parallel aggregate operations. Stream流是一個來自數據源的元素隊列並支持聚合操作
Stream流中常用方法的分類
- 1.中間操作
- 2.終止操作
Stream的常用中間操作
- 1.peek()--消費流中的每一個元素
List<Integer> list = Arrays.asList(6, 5, 5, 1, 4);
list.stream().peek(i -> System.out.println(i)).forEach(i-> System.out.println(i));
- 2.map() mapToInt() mapToDouble()等等--將流中的每一個元素映射為另一個元素
int[] nums={1,2,3,5,6}; int sum = IntStream.of(nums).map(i->i*2).sum();
- 3.filter()--將流中滿足要求的元素過濾出來
List<Integer> list = Arrays.asList(6, 5, 5, 1, 4);
list.stream().filter(integer -> integer>1).forEach(System.out::println);
- 4.sort()--將流中的元素按一定的規則排序
List<Integer> list = Arrays.asList(6, 5, 5, 1, 4);
List<Integer> collect = list.stream().sorted((o1, o2) -> o1 - o2).collect(Collectors.toList());
- 5.distinct()--去重
List<Integer> list = Arrays.asList(6, 5, 5, 1, 4);
list.stream().dinstinct().forEach(System.out::println)
- 6.limit()--截斷流只保留指定個數的元素
List<Integer> list = Arrays.asList(6, 5, 5, 1, 4);
list.stream().limit(1).forEach(System.out::println);
Stream的常用的終止操作
- 1.count()-獲取流中元素的個數
List<Integer> list = Arrays.asList(1, 2, 3, 5, 6); long count = list.stream().count();
- 2.reduce()-將流中所有的元素合並為一個元素,可用於累加求和,求乘積等等
List<Integer> list = Arrays.asList(1, 2, 3, 5, 6);
Integer reduce = list.stream().reduce((integer, integer2) -> integer + integer2).get();
- 3.forEach()-遍歷流中的所有元素
List<Integer> list = Arrays.asList(1, 2, 3, 5, 6);
list.stream().forEach(System.out::println);
- 4.max()-求出流中元素的最大值
List<Integer> list = Arrays.asList(1, 2, 3, 5, 6);
Integer max = list.stream().max((s1, s2) -> s1 - s2).get();
- 5.min()-求出流中元素的最小值
List<Integer> list = Arrays.asList(1, 2, 3, 5, 6);
Integer min = list.stream().max((o1, o2) -> o2 - o1).get();
- 6.anyMaych()/allMatch()/noneMatch()--匹配元素中的值,返回boolean類型
List<Integer> list = Arrays.asList(1, 2, 3, 5, 6); boolean b = list.stream().noneMatch((x) -> x.intValue() == 1); boolean b = list.stream().allMatch((x) -> x.intValue() == 1); boolean b = list.stream().anyMatch((x) -> x.intValue() == 1);
- 7.collect()--收集流中的元素通過Collectors這個工具類處理
List<Integer> list = Arrays.asList(1, 2, 3, 5, 6); //求平均數 Double average= list.stream().collect(Collectors.averagingInt(x -> x.intValue())); //求分組 Double average= list.stream().collect(Collectors.groupinngby(x -> x.intValue())); //收集成一個List List<Integer> collect = list.stream().sorted((o1, o2) -> o1 - o2).collect(Collectors.toList());
- 8.summerizing() summerizing中封裝了很多計算的方法,例如 求和,求平均數等等
Double sum_= list.stream().collect(Collectors.summarizingInt(value -> value.intValue())).getAve
