jdk1.8新特性之——Lambda表达式、Stream API

33 篇文章 0 订阅
30 篇文章 0 订阅

Lambda表达式:
Lambda 是一个匿名函数,我们可以把 Lambda表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。可以写出更简洁、更灵活的代码。

格式:
(parameters) -> expression
(parameters) ->{ statements; }
“ ->” , 该操作符被称为 Lambda 操作符或箭头操作符。它将 Lambda 分为两个部分:
左侧: 指定了 Lambda 表达式需要的所有参数
右侧: 指定了 Lambda 体,即 Lambda 表达式要执行的功能。

例:
public class MyTest {
    public static void main(String[] args) {
        MyInterface myInterface = new MyInterface() {
            @Override
            public void show(int a, int b) {
                System.out.println(a + b);
            }
        };
        myInterface.show(10, 20);
        
        MyInterface myInterface3 = (x, y) -> System.out.println(x + y);     
        MyInterface myInterface2 = (int x, int y) -> System.out.println(x + y);   
          
        MyInterface myInterface4 = (int x, int y) -> {
            System.out.println(x + y);
        };
      
        MyInterface myInterface5 = (int x, int y) -> {
            System.out.println(x + y);
            System.out.println(x-y);
            System.out.println(x*y);
        };
        myInterface2.show(10, 2000);
    }
}
@FunctionalInterface
public interface MyInterface {
    void show(int a,int b);
}

函数式接口:
Lambda 需要 函数式接口的支持
函数式接口:这个接口中,仅仅只有 一个抽象方法
函数式接口可以使用注解 @FunctionalInterface 来检测这个接口是不是函数式接口

Consumer<T> 消费型接口 有一个参数 没有返回值
Supplier<T> 供给型接口 没有参数有返回值
Function<T, R> 函数型接口 T是参数,R是返回值
Predicate<T> 断言型接口 T是参数 返回值boolean类型
例:
public class test1 {
    public static void main(String[] args) {
     
       new Consumer<String>(){
            @Override
         public void accept(String s) {
                System.out.println(s);
           }
        }.accept("abc");
        
        Consumer<String> tConsumer = (s) -> System.out.println(s);
        tConsumer.accept("aaaa");
    
        Supplier<Integer> supplier = () -> 10 * 20;
              
        Function<Integer,String> function=(t)->"abc"+t;
        String apply = function.apply(10);
        System.out.println(apply);
       
        Predicate<Integer> predicate = integer -> integer < 0;
        boolean test = predicate.test(10);
        System.out.println(test);

    }
}

方法引用:
当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用,
方法引用使用操作符 “ ::” 将方法名和对象或类的名字分隔开来。

写法:
     对象::实例方法
     类::静态方法
     类::实例方法
例:
public class test2 {
    public static void main(String[] args) {
       
        BiFunction<String, String, String> function = new BiFunction<String, String, String>() {

            @Override           
            public String apply(String s, String s2) {
                return s.concat(s2);
            }
        };

        BiFunction<String, String, String> function2 = (s, s2) -> s.concat(s2);
        BiFunction<String, String, String> function3 =String::concat;       
        Consumer<String> consumer=System.out::println;      
        BinaryOperator<Double> doubleBinaryOperator=Math::max;
        BiFunction<String, String, String> function5 = String::concat;

    }
}

构造器引用:
与函数式接口相结合,自动与函数式接口中方法兼容。可以把构造器引用赋值给定义的方法,构造器参数列表要与接口中抽象方法的参数列表一致。

格式:ClassName::new
例:
public class test3 {
    public static void main(String[] args) {
        Supplier<Student> supplier = new Supplier<Student>() {
            @Override
            public Student get() {
                return new Student();
            }
        };
               
        Student student = supplier.get();
        Supplier<Student> supplier = () -> new Student();
        supplier.get();

        //构造引用
        Supplier<Student> supplier2 = Student::new;
        BiFunction<String, Integer, Student> biFunction = new BiFunction<String, Integer, Student>() {
            @Override
            public Student apply(String s, Integer integer) {
                return new Student(s, integer);
            }
        };

        BiFunction<String, Integer, Student> biFunction2 = (s, integer) -> new Student(s, integer);
        BiFunction<String, Integer, Student> biFunction3 = Student::new;

    }
}
public class Student {
    private String name;
    private int age;
    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Stream API:
Stream API 提供了一种高效且易于使用的处理数据的方式,使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。
Stream 流:
是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
集合讲的是数据,流讲的是计算。

注意:
	1、Stream 自己不会存储元素。
	2、Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
	3、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、由值创建流
		 public static<T> Stream<T> of(T... values)   返回一个流 
		 //可以使用静态方法 Stream.of()				  通过显示值创建一个流。
		 //它可以接收任意数量的参数。
		 
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)  生成

例:
public class test {
    public static void main(String[] args) {
       
        List<Integer> list = Arrays.asList(10, 20, 30, 40, 1, 0, 9);
        Stream<Integer> stream = list.stream();
        
        Stream<Integer> stream1 = Arrays.stream(new Integer[]{20, 30, 40, 50, 60, 1, 0});
   
        Stream<Integer> integerStream = Stream.of(20, 30, 50, 60, 10);
        Stream<List<Integer>> list1 = Stream.of(list);
        System.out.println("-------------------------");    
          
        Stream<Integer> iterate = Stream.iterate(1, integer -> integer += 1);   
        Stream<Integer> limit = iterate.limit(10);
    
        limit.forEach(System.out::println);
        System.out.println("-------------------");
    
        Stream<Double> stream2 = Stream.generate(() -> Math.random()); //生成无限流     
        Stream<Double> limit1 = stream2.limit(5);
     
        limit1.forEach(System.out::println);

    }
}

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 的终止操作:

1、查找与匹配
	allMatch(Predicate p)	检查是否匹配所有元素,比如判断 所有员工的年龄都是17岁 如果有一个不是,就返回false
	anyMatch(Predicate p)	检查是否至少匹配一个元素,比如判断是否有姓王的员工,如果至少有一个就返回true
	noneMatch(Predicate p)	检查是否没有匹配所有元素,比如判断所有员工的工资都是否都是高于3000 如果有一个人低于3000 就返回false
	findFirst()				返回第一个元素 ,比如获取工资最高的人,或者获取工资最高的值是
	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 模式)
	   
3、收集
	collect(Collector c)	
		将流转换为其他形式。接收一个 Collector接口的实现,
		用于给Stream中元素做汇总的方法
	
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());
		
	Integer	summingInt()	对流中元素的整数属性求和
		例: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));
		   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)));
	
5、归约产生的类型:
	reducing() 从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值
	例:inttotal=list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum));
		
6、转换函数返回的类型 
	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));

程序小练习:

1、归约
public class test2 {
    public static void main(String[] args) {
        
        List<Integer> list = Arrays.asList(10, 20, 30, 40, 50, 60);
        Integer reduce = list.stream().reduce(0, (a, b) -> a + b);
        System.out.println(reduce);

        System.out.println("----------------------");
        Optional<Integer> reduce1 = list.stream().reduce(new BinaryOperator<Integer>() {
            @Override
            public Integer apply(Integer a, Integer b) {
                return a + b;
            }
        });
        System.out.println(reduce1.get());

        //求出员工的工资总和
        List<Employee> emps = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六1", 8, 7777.77),
                new Employee(104, "赵六2", 81, 7777.77),
                new Employee(104, "赵六3", 82, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );
        Stream<Employee> stream = emps.stream();
        Stream<Double> doubleStream = stream.map(ele -> ele.getSalary());
        Double reduce2 = doubleStream.reduce(0.0, (a, b) -> a + b);
        System.out.println(reduce2);
    
    }
}
public class Employee {

	private int id; 		 //员工的id
	private 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 "测试方法引用!";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		long temp;
		temp = Double.doubleToLongBits(salary);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (age != other.age)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status
				+ "]";
	}
	//枚举
	public enum Status {
		FREE, 		//空闲
		BUSY,	 	//繁忙
		VOCATION;	//休假
	}
}
2、给定一个数字列表,如何返回一个由每个数的平方构成的列表呢?
public class test2 {
    public static void main(String[] args) {
       
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        Stream<Integer> stream = list.stream();
        stream.map(integer -> {            
            return integer * integer;
        }).forEach(System.out::println);
               
    }
}
3、怎样用 map () 和 reduce () 方法数一数流中有多少个Employee呢?
public class test3 {
    public static void main(String[] args) {
       
        List<Employee> emps = Arrays.asList(
                new Employee(1, "张三1", 20, 88),
                new Employee(12, "张三2", 202, 88),
                new Employee(15, "张三3", 203, 88),
                new Employee(16, "张三4", 205, 88),
                new Employee(17, "张三5", 206, 88),
                new Employee(18, "张三6", 207, 88)
        );
        System.out.println("----------------------------");      
        Stream<Employee> stream1 = emps.stream();
        Stream<Integer> integerStream = stream1.map(e -> 1);
        Integer reduce = integerStream.reduce(0, (a, b) -> a + b);
        System.out.println(reduce);
        long count = emps.stream().count();

        Long collect = emps.stream().collect(Collectors.counting());

    }
}
public class Employee {
		private int id;
		private String name;
		private int age;
		private double salary;

	public Employee() {
	}

	public Employee(int id, String name, int age, double salary) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	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;
	}

	@Override
	public String toString() {
		return "Employee{" +
				"id=" + id +
				", name='" + name + '\'' +
				", age=" + age +
				", salary=" + salary +
				'}';
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值