1. 什么是Lambda
概念:允许把函数作为一个方法的参数
<函数式接口> <变量名> = (参数1,参数2…)->{方法体}
Runnable task = ()->{System.out.println("子线程启动");};
Thread t2 = new Thread(task);
t2.start();
2. 函数式接口
Consumer接口 没有入参没有出参的方法
Consumer<String> con = (s)->System.out.println(s);
con.accept("hello");
Supplier接口 没有入参只有出参
Supplier<Integer> sup = ()->{
int count = 0;
for(int i =1;i<=50;i++) {
count = count+i;
}
return count;
};
Function<入参,出参>接口 有入参有出参
Function<Employee, String> fun = emp->emp.getName();
Predicate接口 有入参出参为Boolean类型
Predicate<Integer> pre = (s)->{
if(s > 10) {
return true;
}else {
return false;
}
};
pre.test(14);
3. 方法引用
//1.对象::实例方法名
Consumer<String> con2 = System.out::println;
con2.accept("yingyy");
//2.类名::静态方法
Comparator<Integer> com2 = Integer::compare;
int result = com1.compare(1, 2);
//3.类名::实例方法名
Function<Employee, String> fun1 = Employee::getName;
//4.类名::new 类名::构造方法
Supplier<Employee> supp1 = Employee::new;
4. Stream
中间操作
//中间操作
System.out.println("---------limit-------");
list.stream().limit(1).filter((s)->s.startsWith("z")).forEach(System.out::println);
System.out.println("-------dinstinct-------");//利用hashcode和equals筛选
list.stream().distinct().forEach(System.out::println);
System.out.println("--------map----------");
list.stream().map((emp)->emp.getClass()).forEach(System.out::println);
System.out.println("----------sort--------");
list1.stream().sorted((x,y)->Integer.compare(x.getAge(), y.getAge())).forEach(System.out::println);
终止操作
long count = list.stream().filter((s)->s.length()>3).count();
System.out.println(count);
System.out.println("---------anymatch--------");
Boolean bool = list.stream().filter((s)->s.length()>=3).anyMatch((s)->s.startsWith("s"));
System.out.println(bool);
System.out.println("-------allmatch------");
Boolean b2 = list.stream().filter((s)->s.length()>3).allMatch((s)->s.contains("s"));
System.out.println(b2);
System.out.println("----------nonematch-------");
Boolean b3 = list.stream().filter((s)->s.length()>=3).noneMatch((s)->s.contains("A"));
System.out.println("-----------findfirst--------");
String mss = list.stream().findFirst().get();
System.out.println(mss);
System.out.println("--------findAny---------");
String sss = list.stream().findAny().get();
System.out.println(sss);
System.out.println("-------min-------");
Optional<Emp> max = list1.stream().max((e1,e2)->e1.getAge()-e2.getAge());
System.out.println(max.get());
System.out.println("---------max--------");
Optional<Emp> min = list1.stream().min((e1,e2)->e1.getAge()-e2.getAge());
System.out.println(min.get());
多线程stream
List<String> list = new ArrayList<>();
for(int i =0;i<100000;i++) {
UUID u = UUID.randomUUID();
list.add(u.toString());
}
System.out.println("并行");
long start = System.currentTimeMillis();
long count = list.parallelStream().sorted().count();//并行排序
System.out.println("排序了:"+count);
long end = System.currentTimeMillis();
System.out.println("同时:"+(end-start));