300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > JDK1.8新特性之Lambda表达式+Stream流+函数式接口

JDK1.8新特性之Lambda表达式+Stream流+函数式接口

时间:2023-05-09 22:38:41

相关推荐

JDK1.8新特性之Lambda表达式+Stream流+函数式接口

一.Lambda表达式

Lambda表达式,是JDK1.8引入的一种语法,这种语法可以对匿名内部类的写法,进行简写。

1.快速入门

package org.westos.demo2;import java.util.ArrayList;import parator;public class MyTest {public static void main(String[] args) {ArrayList<Integer> list = new ArrayList<>();list.add(300);list.add(305);list.add(250);list.sort(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {//升序排列//具体实现逻辑,最核心的代码return o1-o2;}});System.out.println(list);list.sort((o1,o2)->o2-o1);System.out.println(list);}}

2.语法

(int a,int b)->{具体的重写抽象方法的逻辑}Lambda表达式的语法JDK1.8 引入了一个箭头符号 ->这个箭头符号 将Lambda表达式分为 左右两部分。 左边->右边左边:写的是你实现的这个接口中的抽象方法的 形参列表右边:写的是你对接口中这个抽象方法的具体实现逻辑。

案例一:

package org.westos.demo8;public class MyTest {public static void main(String[] args) {MyInterface myInterface = new MyInterface() {@Overridepublic void show(int a, int b) {//核心的代码,就是这个具体的实现逻辑System.out.println(a+b);}};//第一步简写MyInterface myInterface2 = (int a, int b)->{System.out.println(a+b);};//第二步省略,省略形参的数据类型MyInterface myInterface3=(a,b)->{//核心的代码,就是这个具体的实现逻辑System.out.println(a+b);};//第三步省略:如果只有一行,可以省略大括号MyInterface myInterface4=(a,b)-> System.out.println(a+b);}}package org.westos.demo8;interface MyInterface {public abstract void show(int a,int b);}

案例二:

package org.westos.demo8;public class MyTest2 {public static void main(String[] args) {MyInterface2 myInterface = new MyInterface2(){@Overridepublic int show(int a, int b) {//实现逻辑,最核心的代码return a-b;}};//第一步简写MyInterface2 myInterface2=(int a,int b)->{return a-b;};//第二步简写:省略形参的数据类型MyInterface2 myInterface3=(a,b)->{return a-b;};//第三步简写:如果只有一行代码,{}和return都可省略MyInterface2 myInterface4=(a,b)->a-b;//如果不止一行,那么{}和return不可省略MyInterface2 myInterface5=(a,b)->{a+=100;return a-b;};}}package org.westos.demo8;interface MyInterface2 {public abstract int show(int a,int b);}

案例三:

package org.westos.demo9;public class MyTest {public static void main(String[] args) {MyInterface myInterface = new MyInterface(){@Overridepublic int show(int a) {return a+100;}};MyInterface myInterface1=(int a)->{return a+100;};MyInterface myInterface2=(a)->{return a+100; };//如果形参只有一个,那么括号可以省略不写MyInterface myInterface3=a->a+100;}}interface MyInterface{public abstract int show(int a);}

3.lambda表达式作为参数传递

package org.westos.demo9;import java.util.Arrays;import parator;public class MyTest2 {public static void main(String[] args) {//lambda表达式作为参数传递Integer[] arr={200,100,300};Comparator<Integer> integerComparator = new Comparator<Integer>(){@Overridepublic int compare(Integer a, Integer b) {//升序排列return a-b;}};Arrays.sort(arr,integerComparator);for (Integer integer : arr) {System.out.println(integer);}System.out.println("===========================");Comparator<Integer> comparator = new Comparator<Integer>() {@Overridepublic int compare(Integer a, Integer b) {return b-a;}};Comparator<Integer> comparator2 =(a,b)->b-a;Arrays.sort(arr,comparator2);for (Integer integer : arr) {System.out.println(integer);}System.out.println("===========================");//也可以讲lambda表达式直接传入Arrays.sort(arr,(a,b)->b-a);}}

4.Lambda表达式的使用限制

Lambda表达式的使用限制:Lambda表达式,需要函数式接口的支持。函数式接口:这个接口中,只有一个抽象方法,这种接口我们就称之为函数式接口。有一个注解 @FunctionalInterface 可以检测这个接口是不是一个函数式接口

package org.westos.demo91;public class MyTest {public static void main(String[] args) {/*Lambda表达式的使用限制:Lambda表达式,需要函数式接口的支持。函数式接口:这个接口中,只有一个抽象方法,这种接口我们就称之为函数式接口。有一个注解 @FunctionalInterface 可以检测这个接口是不是一个函数式接口*/MyInterface myInterface = new MyInterface(){@Overridepublic void haha(int a) {System.out.println("哈哈");}@Overridepublic void hehe(int b) {System.out.println("呵呵");}};//不能使用Lambda表达式,因为形参无法确信后面的具体实现逻辑//MyInterface myInterface1=(a)->{};//JDK1.8,之后,提供了很多的函数式接口。来作为参数传递。Consumer<Integer> consumer = new Consumer<Integer>() {@Overridepublic void accept(Integer integer) {System.out.println(integer);}};Consumer<Integer> consumer1=integer -> System.out.println(integer);// Predicate<T> 断言型接口//判断参数是不是满足自己实现的逻辑Predicate<String> predicate=new Predicate<String>() {@Overridepublic boolean test(String s){return new String().startsWith(s);}};System.out.println("======================");Predicate predicate2 = s -> new String().startsWith("aa");}}//@FunctionalInterface//这个注解可以检测该接口是不是一个函数式接口,报错就证明不是interface MyInterface{public abstract void haha(int a);public abstract void hehe(int b);}

5.方法引用

方法引用:是对Lambda表达式的进一步简写。分为如下三种主要使用情况:对象::实例方法类::静态方法类::实例方法

(1)对象::实例方法

package org.westos.demo92;import java.io.PrintStream;import java.util.function.Consumer;public class MyTest {public static void main(String[] args) {Consumer<String> consumer = new Consumer<String>(){@Overridepublic void accept(String s) {PrintStream out = System.out;out.println(s);}};consumer.accept("aaa");Consumer<String> consumer1=s-> System.out.println(s);consumer1.accept("啊哈,金色传说");//方法引用Consumer<String> consumer2=System.out::println;consumer2.accept("这次运气不太好");//方法引用:你对接口中的抽象方法 public void accept(String s) 的具体实现逻辑: System.out.println(x);//accept()抽象方法:有一个参数,无返回值//这个抽象方法的具体实现,System.out.println(s); 你的实现逻辑,用了一个对象 PrintStream//out.print(s)这个方法返回值也是void 然后他也是一个参数。//那么println(x)方法的返回值和参数列表 正好跟你重写的这个accept(String s)方法的返回值和参数列表一致,那么我就可以使用方法引用进行简写//语法 对象::实例方法Consumer<String> consumer3=System.out::println;consumer3.accept("11111");}}

(2)类名::静态方法

package org.westos.demo92;import java.util.function.BinaryOperator;public class MyTest2 {public static void main(String[] args) {BinaryOperator<Double> binaryOperator = new BinaryOperator<Double>(){@Overridepublic Double apply(Double a, Double b) {double max = Math.max(a, b);return max;}};BinaryOperator<Double> binaryOperator1=(a,b)->Math.max(a,b);System.out.println("===============");//语法 类名::静态方法BinaryOperator<Double> binaryOperator2=Math::max;}}

package org.westos.demo92;import parator;public class MyTest4 {public static void main(String[] args) {Comparator<Integer> comparator = new Comparator<Integer>() {@Overridepublic int compare(Integer a , Integer b) {return pare(a,b);}};Comparator<Integer> comparator1=(a,b)->pare(a,b);Comparator<Integer> comparator2=Integer::compareTo;}}

(3)类名::实例方法

package org.westos.demo92;import parator;public class MyTest5 {public static void main(String[] args) {//类名::实例方法Comparator<String> comparator = new Comparator<String>(){@Overridepublic int compare(String s1, String s2){return pareTo(s2);}};Comparator<String> comparator1=(s1,s2)->pareTo(s2);//方法引用: 类名::实例方法//我们重写接口中的方法,传入的两个参数。一个参数作为了调用者,一个参数作为了传入者。Comparator<String> comparator2=String::compareTo;System.out.println("==================");Comparator<String> comparator3 = new Comparator<String>() {@Overridepublic int compare(String s1, String s2) {return s1.indexOf(s2);}};Comparator<String> comparator4=(s1,s2)->s1.indexOf(s2);Comparator<String> comparator5=String::indexOf;}}

6.构造方法引用

格式返回值类型::new

package org.westos.demo4;import java.util.function.BiFunction;import java.util.function.Supplier;public class MyTest {public static void main(String[] args) {//构造方法引用://格式 返回值类型::new//1.获取student对象,采用匿名内部类形式Supplier<Student> supplier = new Supplier<Student>() {@Overridepublic Student get() {//方法的具体实现逻辑//new了一个对象,没有参数,返回值是Student类型,正好和get()方法保持一致Student student = new Student();return student;}};//调用空参构造,打印地址值Student student = supplier.get();System.out.println(student);System.out.println("==========================");//2.采用lambda表达式进行简写Supplier<Student> supplier1 =()->new Student();System.out.println("================");//3.采用构造方法引用进行简写//方法的具体实现逻辑是://new了一个对象,没有参数,返回值是Student类型,正好和get()方法保持一致Supplier<Student> supplier2=Student::new;System.out.println("==========================");Student student1 = new Student("李白", 22);//BiFunction<T, U, R> T是方法的第一个形参类型,U是方法的第二个形参类型 R是方法的返回 值类型BiFunction<String, Integer, Student> function = new BiFunction<String, Integer, Student>() {@Overridepublic Student apply(String name, Integer age) {return new Student(name,age);}};Student student2 = function.apply("杜甫", 33);System.out.println(student2);System.out.println("==========================");BiFunction<String, Integer, Student> function1 =(name,age)->new Student(name,age);BiFunction<String, Integer, Student> function2 =Student::new;}}

二.Stream流

1.概述

IO流操作的是文件,本质是字节数据的流动;Stream流操作的是集合或者数组中的元素;Stream流的出现,是为了我们更加方便的对集合中的元素进行操作(增删改查)。我们要使用Stream流,得分三个阶段1、获取Stream流;2、中间环节的操作;3、终止操作。

2.获取Stream流

package org.westos.demo5;import java.util.Arrays;import java.util.List;import java.util.function.Consumer;import java.util.function.Supplier;import java.util.function.UnaryOperator;import java.util.stream.IntStream;import java.util.stream.Stream;public class MyTest {public static void main(String[] args) {/** 我们要使用Stream流,得分三个阶段1、获取Stream流;2、中间环节的操作;3、终止操作。* *//*获取Stream流:1.通过集合中的stream()方法来获取Stream流** *///首先要有一个容器List<Integer> list = Arrays.asList(100, 300, 200);//让stream流和集合相关联Stream<Integer> stream = list.stream();//方式二:通过Arrays里的stream方法来获取Stream流Integer[] arr={100,300,200};Stream<Integer> stream1 = Arrays.stream(arr);//方式三:通过Stream里的静态方法Stream<Integer> stream2 = Stream.of(100, 300, 200);Stream<List<Integer>> stream3 = Stream.of(list);Stream<Integer> stream4 = Stream.of(arr);//方式四:获取无限流//参数一表示从哪里开始Stream<Integer> iterate = Stream.iterate(100, new UnaryOperator<Integer>() {@Overridepublic Integer apply(Integer integer) {return integer + 1;}});//Stream.iterate(100,integer -> integer+1);//中间操作//从100打印到299,参数表示长度Stream<Integer> limit = iterate.limit(200);//终止操作limit.forEach(new Consumer<Integer>() {@Overridepublic void accept(Integer integer) {System.out.println(integer);}});//limit.forEach(System.out::println);System.out.println("=================");//方式五:获取无限流Stream<Double> generate = Stream.generate(new Supplier<Double>() {@Overridepublic Double get() {double random = Math.random();return random;}});Stream<Double> generate2 = Stream.generate(()->Math.random());Stream<Double> generate3 =Stream.generate(Math::random);generate.forEach(new Consumer<Double>() {@Overridepublic void accept(Double aDouble) {System.out.println(aDouble);}});//中间操作Stream<Double> limit1 = generate.limit(10);generate.forEach(aDouble -> System.out.println(aDouble));generate.forEach(System.out::println);}}

3.中间操作

雇员类

package org.westos.demo7;import java.util.Objects;public class Employee{private int id; //员工的idprivate String name; //员工的姓名private int age; //员工的年龄private double salary; //员工的工资//枚举private Status status; //员工的状态public Employee() {}public Employee(String name) {this.name = name;}public Employee(String name, int age) {this.name = name;this.age = age;}public Employee(int id, String name, int age, double salary) {this.id = id;this.name = name;this.age = age;this.salary = salary;}public Employee(int id, String name, int age, double salary, Status status) {this.id = id;this.name = name;this.age = age;this.salary = salary;this.status = status;}public Status getStatus() {return status;}public void setStatus(Status status) {this.status = status;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public String show() {return "测试方法引用!";}@Overridepublic String toString() {return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status+ "]";}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Employee employee = (Employee) o;return id == employee.id &&age == employee.age &&pare(employee.salary, salary) == 0 &&Objects.equals(name, employee.name) &&status == employee.status;}@Overridepublic int hashCode() {return Objects.hash(id, name, age, salary, status);}//枚举public enum Status {FREE, //空闲BUSY, //繁忙VOCATION;//休假}}

(1)去重和过滤

filter和distinct

package org.westos.demo7;import java.util.Arrays;import java.util.List;import java.util.function.Consumer;import java.util.stream.Stream;public class MyTest {public static void main(String[] args) {//去重和过滤/*Stream流的中间环节的操作,不会对原有的集合容器有任何改变*/List<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(105, "田七", 38, 5555.55));//获取Stream流//1.去重Stream<Employee> stream = list.stream();//中间操作:返回一个持有新结果的流//filter(Predicate p) 过滤 接收 Lambda ,从流中排除某些元素。//获取工资大于6000员工Stream<Employee> employeeStream = stream.filter(employee -> employee.getSalary() > 6000);/*employeeStream.forEach(new Consumer<Employee>() {@Overridepublic void accept(Employee employee) {System.out.println(employee);}});employeeStream.forEach(employee->System.out.println(employee);)*///employeeStream.forEach(System.out::println);/** Employee [id=102, name=李四, age=59, salary=6666.66, status=null]Employee [id=101, name=张三, age=18, salary=9999.99, status=null]Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]* */// distinct() 去重,需要Employee类 重写hashCode()和equals()方法Stream<Employee> distinct = employeeStream.distinct();distinct.forEach(System.out::println);System.out.println("=====================================");List<Employee> list2 = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77), //0x001new Employee(104, "赵六", 8, 7777.77), //0x002new Employee(105, "田七", 38, 5555.55) //0x003);//先过滤再去重Stream<Employee> stream2 = list2.stream();stream2.filter(employee -> employee.getSalary()>6000).distinct().forEach(System.out::println);//过滤出姓找的员工List<Employee> list3 = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77), //0x001new Employee(104, "赵六", 8, 7777.77), //0x002new Employee(105, "田七", 38, 5555.55) //0x003);Stream<Employee> stream3 = list3.stream();stream3.filter(employee -> employee.getName().startsWith("赵")).forEach(System.out::println);}}

(2)截断流和跳过元素

limit( long maxSize)截断流,使其元素不超过给定数量。skip( long n)跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit (n) 互补注意;终止操作不执行,中间环节就不执行,体现的就是一种延迟加载的思想,你要用的时候,我再去操作

package org.westos.demo7;import java.util.Arrays;import java.util.List;import java.util.function.Predicate;import java.util.stream.Stream;public class MyTest2 {public static void main(String[] args) {//截断流List<Integer> list = Arrays.asList(300, 100, 200,50,233);Stream<Integer> stream = list.stream();//Stream<Integer> stream1 = stream.filter(integer -> integer > 200);//limit(3)从头开始截断三个Stream<Integer> limit = stream.limit(3);limit.forEach(System.out::println);// 300 100 200System.out.println("===========================");List<Employee> list2 = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(105, "田七", 38, 5555.55));list2.stream().filter(employee -> employee.getAge()>20).limit(1).forEach(System.out::println);System.out.println("===========================");List<Integer> list3 = Arrays.asList(10, 20, 30, 40, 50);Stream<Integer> stream3 = list3.stream();//stream3.filter(integer -> integer>20).forEach(System.out::println);// 30 40 50//skip(2) 跳过前两个不要,取后面剩下的,跟limit()互补stream3.skip(2).forEach(System.out::println);System.out.println("===================");//注意;终止操作不执行,中间环节就不执行,体现的就是一种延迟加载的思想,你要用的时候,我再去操作List<Integer> list4 = Arrays.asList(10, 20, 30, 40, 50);Stream<Integer> stream4 = list4.stream();Stream<Integer> integerStream = stream4.skip(2).filter(new Predicate<Integer>() {@Overridepublic boolean test(Integer integer) {System.out.println("中间环节进行了");return integer > 10;}});integerStream.forEach(System.out::println);/** 中间环节进行了30中间环节进行了40中间环节进行了50*/}}

(3)map(Function f)和flatMap(Function f)

map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。获取集合中的元素,应用到一个方法上。flatMap(Function f)接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流.

package org.westos.demo7;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;public class MyTest3 {public static void main(String[] args) {// map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。//提前集合中的元素,应用到一个方法上。List<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(105, "田七", 38, 5555.55));/* Stream<Employee> stream = list.stream();Stream<String> stringStream = stream.map(employee -> employee.getName());stringStream.distinct().forEach(System.out::println);*/list.stream().map(employee -> employee.getAge()).distinct().forEach(System.out::println);System.out.println("==============================");//把集合中的元素变成大写List<String> list2 = Arrays.asList("aaa", "bbb", "ccc", "ddd");//map:获取集合中的元素,应用到一个方法上list2.stream().map(s -> s.toUpperCase()).forEach(System.out::println);System.out.println("=============================="); }}

package org.westos.demo7;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.function.Consumer;import java.util.function.Function;import java.util.stream.Stream;public class MyTest4 {public static void main(String[] args) {List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd");//提取集合中的每一个元素,把这个字符串,截取成一个个字符,放到换一个集合中,在把这个集合转换成Stream流返回。//"aaa" --->'a' 'a' 'a' ---> ['a','a','a']--->流Stream<String> stream = list.stream();//R apply(T t) 第一个参数为调用者 类名::实例方法Stream<Stream<Character>> streamStream = stream.map(new Function<String, Stream<Character>>() {@Overridepublic Stream<Character> apply(String s) {//System.out.println(s);// 提取集合中的每一个元素,讲这个字符串,截取成一个个字符,放到一个集合中,在把这个集合转换成Stream流返回。//这个操作,没有现成方法可用,那我们自己就编写一个return getStreamChar(s);}});//外层拿到每一个数组,streamStream.forEach(new Consumer<Stream<Character>>() {@Overridepublic void accept(Stream<Character> characterStream) {characterStream.forEach(System.out::println);}});System.out.println("=================================");List<String> list2 = Arrays.asList("aaa", "bbb", "ccc", "ddd");//提取集合中的每一个元素,把这个字符串,截取成一个个字符,放到换一个集合中,在把这个集合转换成Stream流返回。Stream<String> stream2 = list2.stream();//拿到整个的流Stream<Character> characterStream = stream2.flatMap(new Function<String, Stream<Character>>() {@Overridepublic Stream<Character> apply(String s) {return getStreamChar(s);}});characterStream.forEach(System.out::println);}public static Stream<Character> getStreamChar(String s) {char[] chars = s.toCharArray();ArrayList<Character> arrayList = new ArrayList<>();for (char c : chars) {arrayList.add(c);}Stream<Character> stream = arrayList.stream();return stream;}}

(4)mapToInt

mapToInt它将每个Integer解包成一个int,mapToInt(ToIntFunction t) 类名::静态方法

package org.westos.demo7;import java.util.Arrays;import java.util.List;import java.util.stream.IntStream;import java.util.stream.Stream;public class MyTest5 {public static void main(String[] args) {//mapToInt//它将每个Integer解包成一个int,//mapToInt(ToIntFunction t) 类名::静态方法List<Integer> list = Arrays.asList(200,30,20,50,999);Stream<Integer> stream = list.stream();//把Integer类型转换为int类型,求平方IntStream intStream = stream.mapToInt(value -> (int) Math.pow(value, 2));intStream.forEach(System.out::println);}}

(5)sorted(Comparator c)

package org.westos.demo7;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;public class MyTest6 {public static void main(String[] args) {List<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(105, "田七", 38, 5555.55));Stream<Employee> stream = list.stream();//自然排序要求元素实现一个Compareble接口//stream.sorted();Stream<Employee> sorted = stream.distinct().sorted((e1, e2) -> e1.getAge() - e2.getAge());sorted.forEach(System.out::println);}}

4.终止操作

终止操作,当我们执行完了中间环节,就想要执行终止操作,来得到中间环节流持有的结果

(1) allMatch(Predicate p)

检查是否全部匹配Predicate断言型接口boolean test(T t);

package org.westos.demo7;import java.util.Arrays;import java.util.List;import java.util.function.Predicate;import java.util.stream.Stream;public class MyTest7 {public static void main(String[] args) {// allMatch(Predicate p) 检查是否匹配所有元素List<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 17, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 17, 7777.77),new Employee(105, "田七", 38, 5555.55));Stream<Employee> stream = list.stream();//检查所有人的年龄是否大于7岁,如果有一个不是, 就返回falseboolean b = stream.allMatch(employee -> employee.getAge() > 7);System.out.println(b);//trueSystem.out.println("=======================");List<Employee> list2 = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 17, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 17, 7777.77),new Employee(105, "田七", 38, 5555.55));//中间操作list2.stream().map(employee -> employee.getName()).forEach(System.out::println);System.out.println("====================================");//终止操作//检查所有人的年龄是不是小于30,只要有一个不小于,就返回falseboolean b1 = list2.stream().allMatch(new Predicate<Employee>() {@Overridepublic boolean test(Employee employee) {return employee.getAge() < 30;}});System.out.println(b1);//false}}

(2)anyMatch(Predicate p)

Predicate断言型接口boolean test(T t);anyMatch(Predicate p) 检查是否至少匹配一个元素 比如判断是否有姓王的员工, 如果至少有一个就返回true

package org.westos.demo7;import java.util.Arrays;import java.util.List;public class MyTest8 {public static void main(String[] args) {// anyMatch(Predicate p) 检查是否至少匹配一个元素 比如判断是否有姓王的员工, 如果至少有一个就返回trueList<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 17, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 17, 7777.77),new Employee(105, "田七", 38, 5555.55));boolean b = list.stream().anyMatch(employee -> employee.getName().startsWith("王"));System.out.println(b);//trueSystem.out.println("==============================");//只要有一个人符合,就返回图trueboolean b1 = list.stream().anyMatch(employee -> employee.getSalary() > 7000);System.out.println(b1);//true}}

(3)noneMatch(Predicate p)

noneMatch(Predicate p) 检查是否没有匹配所有元素 employee.getSalary() < 3000;每个员工的工资如果都高于3000就返回true 如果有一个低于3000 就返回false

package org.westos.demo7;import java.util.Arrays;import java.util.List;public class MyTest9 {public static void main(String[] args) {//检查是否没有匹配所有元素 employee.getSalary() < 3000; 每个员工的工资如果都高于3000// 就返回true 如果有一个低于3000 就返回falseList<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 17, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 17, 7777.77),new Employee(105, "田七", 38, 0.55));//判断是不是没有员工的工资大于1wboolean b = list.stream().noneMatch(employee -> employee.getSalary() > 10000);System.out.println(b);//true}}

(4)查找

findFirst()返回第一个元素 比如获取工资最高的人 或者 获取工资最高的值findAny()返回当前流中的任意元素 比如随便获取一个姓王的员工count()返回流中元素总数

package org.westos.demo7;import java.util.Arrays;import java.util.List;import java.util.Optional;import java.util.stream.Stream;public class MyTest91 {public static void main(String[] args) {//查找List<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 17, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 17, 7777.77),new Employee(105, "田七", 38, 0.55));// findFirst() 返回第一个元素 比如获取工资最高的人 或者 获取工资最高的值是//我要获取工资最高的那个员工Employee// Optional 容器,会把员工放到这个容器中//获取最高工资,要先排序Optional<Employee> first = list.stream().sorted((e1, e2) -> (int) (e2.getSalary() - e1.getSalary())).findFirst();System.out.println(first.get());//Employee [id=101, name=张三, age=18, salary=9999.99, status=null]System.out.println("====================================");Optional<Employee> first1 = list.stream().sorted((e1, e2) -> pare(e2.getSalary(), e1.getSalary())).findFirst();System.out.println(first1.get());//Employee [id=101, name=张三, age=18, salary=9999.99, status=null]System.out.println("====================================");Stream<Double> sorted = list.stream().map(employee -> employee.getSalary()).sorted((e1, e2) -> (int) (e2 - e1));Optional<Double> first2 = sorted.findFirst();System.out.println(first2);//Optional[9999.99]}}

package org.westos.demo7;import java.util.Arrays;import parator;import java.util.List;import java.util.Optional;import java.util.stream.Stream;public class MyTest92 {public static void main(String[] args) {// findAny() 返回当前流中的任意元素 比如随便获取一个姓王的员工List<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "王三", 18, 9999.99),new Employee(101, "王三", 18, 9999.99),new Employee(101, "王三", 18, 9999.99),new Employee(101, "王三", 18, 9999.99),new Employee(101, "王三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "王六", 17, 7777.77),new Employee(104, "王六", 17, 7777.77),new Employee(104, "王六", 17, 7777.77),new Employee(104, "王六", 17, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 17, 7777.77),new Employee(105, "田七", 38, 0.55));String name = list.stream().findAny().get().getName();System.out.println(name);//int size = list.size();//串行流list.stream()//并行流:list.parallelStream()//默认采用的是串行流,从上往下读,所以一直获取到李四Stream<Employee> employeeStream = list.parallelStream().filter(employee -> employee.getSalary() > 5000);Employee employee = employeeStream.findAny().get();System.out.println(employee);System.out.println("=====================================");//count()统计流中的元素个数System.out.println(list.size());System.out.println(list.stream().count());System.out.println(list.stream().distinct().count());System.out.println("=====================================");//获取最小值Optional<Employee> min = list.stream().min(new Comparator<Employee>() {@Overridepublic int compare(Employee e1, Employee e2) {return (int) (e1.getSalary()-e2.getSalary());}});Employee employee1 = min.get();System.out.println(employee1);System.out.println("=====================================");Optional<Double> min1 = list.stream().map(employee2 -> employee2.getSalary()).min(new Comparator<Double>() {@Overridepublic int compare(Double a, Double b) {return (int) (a - b);}});System.out.println(min1.get());}}

(5)累加

2.归约reduce(T iden, BinaryOperator b) 参1 是起始值, 参2 二元运算可以将流中元素反复结合起来,得到一个值。返回 T 比如: 求集合中元素的累加总和 reduce(BinaryOperator b) 这个方法没有起始值可以将流中元素反复结合起来,得到一个值。返回 Optional<T> , 比如你可以算所有员工工资的总和备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它来进行网络搜索而出名。

package org.westos.demo7;import java.util.Arrays;import java.util.List;import java.util.Optional;import java.util.function.BiFunction;import java.util.function.BinaryOperator;public class MyTest93 {public static void main(String[] args) {List<Integer> list = Arrays.asList(10, 20, 30, 400);/* reduce(T iden, BinaryOperator b) 参1 是起始值, 参2 二元运算 可以将流中元素反复结合起来,得到一个值。返回 T 比如:求集合中元素的累加总和*/Optional<Integer> reduce = list.stream().reduce(new BinaryOperator<Integer>() {@Overridepublic Integer apply(Integer a, Integer b) {return a + b;}});System.out.println(reduce.get());//460System.out.println("======================");Optional<Integer> reduce1 = list.stream().reduce((a, b) -> a + b);System.out.println(reduce1);//Optional[460]System.out.println(reduce1.get());//460System.out.println("======================");//参数1:你可以给一个起始值Integer reduce2 = list.stream().reduce(10, (a, b) -> a + b);System.out.println(reduce2);//460System.out.println("=======================================");List<Employee> list2 = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "王三", 18, 9999.99),new Employee(101, "王三", 18, 9999.99),new Employee(101, "王三", 18, 9999.99),new Employee(101, "王三", 18, 9999.99),new Employee(101, "王三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "王六", 17, 7777.77),new Employee(104, "王六", 17, 7777.77),new Employee(104, "王六", 17, 7777.77),new Employee(104, "王六", 17, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 17, 7777.77),new Employee(105, "田七", 38, 0.55));//求员工总工资Double reduce3 = list2.stream().map(employee -> employee.getSalary()).reduce((double) 0, (a, b) -> a + b);System.out.println(reduce3);}}

(6)收集

collect(Collector c)将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例

package org.westos.demo7;import java.util.*;import java.util.stream.Collector;import java.util.stream.Collectors;import java.util.stream.Stream;public class MyTest94 {public static void main(String[] args) {/* collect(Collector c)将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,*/List<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(105, "田七", 38, 5555.55));Stream<String> stringStream = list.stream().map(employee -> employee.getName()).distinct();/*stringStream.forEach(System.out::println);Collector<Object, ?, List<Object>> objectListCollector = Collectors.toList();*///把结果收集到List集合List<String> collect = stringStream.collect(Collectors.toList());System.out.println(collect);//[李四, 张三, 王五, 赵六, 田七]//把结果收集到Set集合System.out.println("================================");Stream<Integer> distinct = list.stream().map(employee -> employee.getAge()).distinct();Set<Integer> collect1 = distinct.collect(Collectors.toSet());System.out.println(collect1);//[18, 38, 8, 59, 28]System.out.println("================================");//收集到指定集合里面Stream<String> distinct1 = list.stream().map(employee -> employee.getName()).distinct();LinkedHashSet<String> collect2 = distinct1.collect(Collectors.toCollection(LinkedHashSet::new));System.out.println(collect2);//[李四, 张三, 王五, 赵六, 田七]System.out.println("================================");}}

(7)拼接和求工资

package org.westos.demo8;import org.westos.demo7.Employee;import java.util.Arrays;import java.util.DoubleSummaryStatistics;import java.util.List;import java.util.Optional;import java.util.stream.Collectors;public class MyTest {public static void main(String[] args) {List<Employee> list = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(105, "田七", 38, 5555.55));List<String> collect = list.stream().map(employee -> employee.getName()).collect(Collectors.toList());System.out.println(collect);System.out.println("============================");//拼接String collect1 = list.stream().map(employee -> employee.getName()).collect(Collectors.joining("-"));System.out.println(collect1);//李四-张三-王五-赵六-赵六-赵六-田七System.out.println("==============================");String collect2 = list.stream().map(employee -> employee.getName()).collect(Collectors.joining("-", "[", "]"));System.out.println(collect2);//[李四-张三-王五-赵六-赵六-赵六-田七]System.out.println("===================================");//求平均工资Double collect3 = list.stream().collect(Collectors.averagingDouble(value -> value.getSalary()));System.out.println(collect3);DoubleSummaryStatistics collect4 = list.stream().collect(Collectors.summarizingDouble(Employee::getSalary));System.out.println(collect4);//求平均工资System.out.println(collect4.getAverage());//求最大工资System.out.println(collect4.getMax());//求最小工资System.out.println(collect4.getMin());//获取总工资System.out.println(collect4.getSum());System.out.println("================");Optional<Employee> collect5 = list.stream().collect(Collectors.maxBy((e1, e2) -> (int) (e1.getSalary() - e2.getSalary())));Employee employee = collect5.get();System.out.println(employee);System.out.println("=======================");Optional<Employee> collect6 = list.stream().collect(Collectors.minBy((e1, e2) -> (int) (e1.getSalary() - e2.getSalary())));Employee employee1 = collect6.get();System.out.println(employee1);}}

5.总结

** Stream API(java.util.stream.*)Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。** 流(Stream) 到底是什么呢?是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。集合讲的是数据,流讲的是计算!*注意:①Stream 自己不会存储元素。②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。** Stream 的操作三个步骤1.创建 Stream一个数据源(如:集合、数组),获取一个流 2.中间操作一个中间操作链,对数据源的数据进行处理 3.终止操作(终端操作)一个终止操作,执行中间操作链,并产生结果** 创建Stream的方式 1.Java8 中的 Collection 接口被扩展,提供了两个获取流的方法:default Stream<E> stream() : 返回一个顺序流default Stream<E> parallelStream() : 返回一个并行流 2.Java8 中的 Arrays 的静态方法 stream() 可以获取数组流:static <T> Stream<T> stream(T[] array): 返回一个流重载形式,能够处理对应基本类型的数组:public static IntStream stream(int[] array) public static LongStream stream(long[] array) public static DoubleStream stream(double[] array) 3.由值创建流,可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。 public static<T> Stream<T> of(T... values) : 返回一个流 4.由函数创建流:创建无限流可以使用静态方法 Stream.iterate()和Stream.generate(), 创建无限流。public static<T> Stream<T> iterate(final T seed, finalUnaryOperator<T> f) 迭代public static<T> Stream<T> generate(Supplier<T> s) 生成** Stream 的中间操作多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”。1.筛选与切片filter(Predicate p) 过滤 接收 Lambda , 从流中排除某些元素。distinct() 去重,通过流所生成元素的 hashCode() 和 equals() 去除重复元素limit(long maxSize) 截断流,使其元素不超过给定数量。skip(long n) 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补2.映射map(Function f)接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。flatMap(Function f)接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流.mapToDouble(ToDoubleFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。mapToInt(ToIntFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。mapToLong(ToLongFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。3.排序sorted()产生一个新流,其中按自然顺序排序 元素实现Compareble接口sorted(Comparator comp)产生一个新流,其中按比较器顺序排序 传入一个比较**Stream 的终止操作终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。1.查找与匹配allMatch(Predicate p)检查是否匹配所有元素 比如判断 所有员工的年龄都是17岁 如果有一个不是,就返回falseanyMatch(Predicate p)检查是否至少匹配一个元素 比如判断是否有姓王的员工,如果至少有一个就返回truenoneMatch(Predicate p)检查是否没有匹配所有元素 employee.getSalary() < 3000; 每个员工的工资如果都高于3000就返回true 如果有一个低于3000 就返回falsefindFirst()返回第一个元素 比如获取工资最高的人 或者 获取工资最高的值是findAny()返回当前流中的任意元素 比如随便获取一个姓王的员工count()返回流中元素总数 max(Comparator c)返回流中最大值 比如:获取最大年龄值min(Comparator c)返回流中最小值 比如:获取最小年龄的值forEach(Consumer c)内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了)2.归约reduce(T iden, BinaryOperator b) 参1 是起始值, 参2 二元运算可以将流中元素反复结合起来,得到一个值。返回 T 比如: 求集合中元素的累加总和 reduce(BinaryOperator b) 这个方法没有起始值可以将流中元素反复结合起来,得到一个值。返回 Optional<T> , 比如你可以算所有员工工资的总和备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它来进行网络搜索而出名。3.收集collect(Collector c)将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下4.Collectors 中的方法List<T> toList()把流中元素收集到List 比如把所有员工的名字通过map()方法提取出来之后,在放到List集合中去例子:List<Employee> emps= list.stream().map(提取名字).collect(Collectors.toList());Set<T> toSet()把流中元素收集到Set 比如把所有员工的名字通过map()方法提取出来之后,在放到Set集合中去例子:Set<Employee> emps= list.stream().collect(Collectors.toSet());Collection<T> toCollection()把流中元素收集到创建的集合 比如把所有员工的名字通过map()方法提取出来之后,在放到自己指定的集合中去例子:Collection<Employee>emps=list.stream().map(提取名字).collect(Collectors.toCollection(ArrayList::new));Long counting()计算流中元素的个数例子:long count = list.stream().collect(Collectors.counting());IntegersummingInt()对流中元素的整数属性求和例子:inttotal=list.stream().collect(Collectors.summingInt(Employee::getSalary));Double averagingInt()计算流中元素Integer属性的平均值例子:doubleavg= list.stream().collect(Collectors.averagingInt(Employee::getSalary));IntSummaryStatistics summarizingInt()收集流中Integer属性的统计值。例子:DoubleSummaryStatistics dss= list.stream().collect(Collectors.summarizingDouble(Employee::getSalary));从DoubleSummaryStatistics 中可以获取最大值,平均值等double average = dss.getAverage();long count = dss.getCount();double max = dss.getMax();String joining() 连接流中每个字符串 比如把所有人的名字提取出来,在通过"-"横杠拼接起来例子:String str= list.stream().map(Employee::getName).collect(Collectors.joining("-"));Optional<T> maxBy() 根据比较器选择最大值 比如求最大工资例子:Optional<Emp>max= list.stream().collect(Collectors.maxBy(comparingInt(Employee::getSalary)));Optional<T> minBy() 根据比较器选择最小值 比如求最小工资例子:Optional<Emp> min = list.stream().collect(Collectors.minBy(comparingInt(Employee::getSalary)));归约产生的类型 reducing() 从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值例子:inttotal=list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum));转换函数返回的类型 collectingAndThen()包裹另一个收集器,对其结果转换函数例子:inthow= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size));Map<K, List<T>> groupingBy() 根据某属性值对流分组,属性为K,结果为V 比如按照 状态分组例子:Map<Emp.Status, List<Emp>> map= list.stream().collect(Collectors.groupingBy(Employee::getStatus));Map<Boolean, List<T>> partitioningBy() 根据true或false进行分区 比如 工资大于等于6000的一个区,小于6000的一个区例子:Map<Boolean,List<Emp>>vd= list.stream().collect(Collectors.partitioningBy(Employee::getSalary));**并行流与串行流并行流就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流。Java 8 中将并行进行了优化,我们可以很容易的对数据进行并行操作。Stream API 可以声明性地通过 parallel() 与sequential() 在并行流与顺序流之间进行切换。

三.函数式接口

1.Consumer

消费型接口对类型为T的对象应用操作,包含方法:void accept(T t)

@FunctionalInterfacepublic interface Consumer<T> {void accept(T t);}

package org.westos.demo;import java.util.function.Consumer;public class MyTest4 {public static void main(String[] args) {Consumer<String> consumer = new Consumer<String>() {@Overridepublic void accept(String s) {System.out.println(s.toUpperCase());}};Consumer<String> consumer2 =s -> s.toUpperCase();consumer2.accept("aaa");}}

2.Supplier

供给型接口,返回什么由抽象方法的实现逻辑决定,没有参数,但是有参数。返回类型为T的对象,包含方法: T get();

@FunctionalInterfacepublic interface Supplier<T> {T get();}

package org.westos.demo;import java.util.function.Supplier;public class MyTest {public static void main(String[] args) {Supplier<Integer> supplier = new Supplier<Integer>() {@Overridepublic Integer get() {return 100;}};Supplier<Integer> supplier2=()->100;}}

3.Predicate

断言型接口,判断参数是否符合抽象方法的实现逻辑,有参数,返回值类型为boolean。确定类型为T的对象是否满足某约束,并返回boolean 值。包含方法boolean test(T t);

@FunctionalInterfacepublic interface Predicate<T> {boolean test(T t);}

package org.westos.demo;import java.util.function.Predicate;public class MyTest2 {public static void main(String[] args) {Predicate<Integer> predicate = new Predicate<Integer>() {@Overridepublic boolean test(Integer integer) {return integer>100;}};Predicate<Integer> predicate2 =integer -> integer>100;}}

4.Function<T, R>

对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法: R apply(T t);

@FunctionalInterfacepublic interface Function<T, R> {R apply(T t);}

package org.westos.demo;import java.util.function.Function;public class MyTest3 {public static void main(String[] args) {Function<Integer, String> function = new Function<Integer, String>() {@Overridepublic String apply(Integer integer) {return String.valueOf(integer);}};Function<Integer, String> function2 =integer -> String.valueOf(integer);String apply = function2.apply(100);System.out.println(apply);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。