package com.example.socket.demo.TEST.Lamda;
import javax.swing.plaf.synth.SynthUI;
import java.awt.dnd.DragGestureEvent;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.*;
/**
*功能描述 联系java8Lamda表达式
* @author kangjinfan
* @date 2019/8/6
*/
public class Lamda {
public static void main(String[] args) {
// changYong();
// 将流转换为list
// list();
// filter
//顾名思义,起过滤筛选的作用
// filter();
// 转换功能
// map();
// 将多个Stream合并为一个Stream
// flatMap();
// 求最大或最小值
// maxmin();
// 统计功能
// count();
// 操作可以实现从一组值中生成一个值
// reduce();
// 收集器
// CollectorsTest();
// 字符串拼接
JoiningTest();
}
//常用方法
public static void changYong(){
Predicate<Integer> predicate = x -> x > 185;
Student student = new Student("9龙", 23, 175);
System.out.println("9龙的身高高于185吗?:" + predicate.test(student.getStature()));//判断
//test只能判断Integer类型
Consumer consumer1 = System.out::println;
Predicate<String> predicate1 = y -> y == "1";
consumer1.accept("输出string判断"+predicate.test(Integer.valueOf(2)));
Consumer<String> consumer = System.out::println;
consumer.accept("命运由我不由天");//输出
Function<Student, String> function = Student::getName;//方法获取姓名
String name = function.apply(student);
System.out.println(name);
consumer.accept("测试consumer=="+name);
Function<Student,Integer> fun = Student::getAge;
Integer age = fun.apply(student);
Consumer consumer2 = System.out::println;
consumer2.accept("继续测试consumer功能"+age);
Supplier<Integer> supplier = () -> Integer.valueOf(BigDecimal.TEN.toString());//工厂方法
System.out.println(supplier.get());
UnaryOperator<Boolean> unaryOperator = uglily -> !uglily;//逻辑非
Boolean apply2 = unaryOperator.apply(true);
System.out.println(apply2);
UnaryOperator<Boolean> unary = xx -> !xx;
Boolean boo = unary.apply(false);
Consumer booConsumer = System.out::println;
booConsumer.accept("测试非逻辑"+boo);
BinaryOperator<Integer> operator = (x, y) -> x + y;//相乘
Integer integer = operator.apply(2, 3);
System.out.println(integer);
BinaryOperator<String> binaryOperator = (z,c) -> z + c;
String bb = binaryOperator.apply("a", "b");
Consumer c = System.out::println;
c.accept("输出String类型相加"+bb);
test(() -> "我是一个演示的函数式接口");
}
/**
* 演示自定义函数式接口使用
*
* @param worker
*/
public static void test(Worker worker) {
String work = worker.work();
System.out.println(work);
}
public interface Worker {
String work();
}
//内部类学生
static class Student{
private String name;
private Integer age;
private Integer stature;
public Student(String name,Integer age,Integer stature){
this.name = name;
this.age = age;
this.stature = stature;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getStature() {
return stature;
}
public void setStature(Integer stature) {
this.stature = stature;
}
}
//将流转换为list。还有toSet(),toMap()等。及早求值
public static void list() {
List<Student> studentList = Stream.of(
new Student("路飞", 22, 175),
new Student("红发", 40, 180),
new Student("白胡子", 50, 185)).collect(Collectors.toList());
System.out.println(studentList);
List<Student> sti = Stream.of(new Student("ce", 10, 100),
new Student("ce1", 11, 200),
new Student("ce2", 12, 300)
).collect(Collectors.toList());
Consumer consumer = System.out::println;
consumer.accept("自创list:"+sti);
}
//filter
//顾名思义,起过滤筛选的作用。内部就是Predicate接口。惰性求值。
// 比如我们筛选出出身高小于180的同学。
public static void filter() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 22, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
List<Student> list = students.stream()
.filter(stu -> stu.getStature() < 180)
.collect(Collectors.toList());
System.out.println(list);
List<Student> listTest = Stream.of(
new Student("测试", 10, 100),
new Student("测试1", 20, 120),
new Student("测试2", 30, 121)
).collect(Collectors.toList());
List<Student> ageStudent = listTest.stream().filter(stu -> stu.getAge()<20).collect(Collectors.toList());
Consumer con = System.out::println;
ageStudent.stream().forEach(aa -> aa.getAge());
con.accept("判断后的list"+ageStudent);
}
// map
// 转换功能,内部就是Function接口。惰性求值
// 例子中将student对象转换为String对象,获取student的名字。
public static void map() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 22, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
List<String> names = students.stream().map(student -> student.getName())
.collect(Collectors.toList());
System.out.println(names);
List<Student> list = Stream.of(
new Student("a", 1, 1),
new Student("b", 2, 2),
new Student("c", 3, 3)
).collect(Collectors.toList());
List<Integer> ageList = list.stream().map(l -> l.getAge()).collect(Collectors.toList());
Consumer con = System.out::println;
con.accept("测试自己写的map"+ageList);
}
// flatMap
// 将多个Stream合并为一个Stream。惰性求值
// 调用Stream.of的静态方法将两个list转换为Stream,再通过flatMap将两个流合并为一个。
public static void flatMap() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 22, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
List<Student> studentList = Stream.of(students,
asList(new Student("艾斯", 25, 183),
new Student("雷利", 48, 176)))
.flatMap(students1 -> students1.stream()).collect(Collectors.toList());
System.out.println(studentList);
List<Student> s1 = Stream.of(
new Student("a", 1, 1),
new Student("b", 2, 2)
).collect(Collectors.toList());
List<Student> s2 = Stream.of(
new Student("c", 3, 3),
new Student("b", 4, 4)
).collect(Collectors.toList());
List<Student> ss = Stream.of(s1,s2).flatMap(s -> s.stream()).collect(Collectors.toList());
Consumer c = System.out::println;
c.accept("自测stream合并"+ss);
}
// max和min
// 我们经常会在集合中求最大或最小值,使用流就很方便。及早求值。
// max、min接收一个Comparator(例子中使用java8自带的静态函数,只需要传进需要比较值即可。)
// 并且返回一个Optional对象,该对象是java8新增的类,专门为了防止null引发的空指针异常。
// 可以使用max.isPresent()判断是否有值;可以使用max.orElse(new Student()),
// 当值为null时就使用给定值;也可以使用max.orElseGet(() -> new Student());
// 这需要传入一个Supplier的lambda表达式。
public static void maxmin() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 22, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
Optional<Student> max = students.stream()
.max(comparing(stu -> stu.getAge()));
Optional<Student> min = students.stream()
.min(comparing(stu -> stu.getAge()));
//判断是否有值
if (max.isPresent()) {
System.out.println(max.get().name);
}
if (min.isPresent()) {
System.out.println(min.get().name);
}
List<Student> s = Stream.of(
new Student("a", 1, 10),
new Student("b", 2, 20),
new Student("c", 3, 30)
).collect(Collectors.toList());
Consumer c = System.out::println;
Long sum = s.stream().map(aa -> aa.getAge() >1).count();
c.accept("年龄大于1的数量"+sum);
Optional<Student> stuMax = s.stream().max(comparing(ss -> ss.getAge()));
if (stuMax.isPresent()){
c.accept("最大值:"+stuMax.get().getAge());
}
Optional<Student> stuMin = s.stream().min(comparing(tt -> tt.getAge()));
if (stuMin.isPresent()){
c.accept("最小值"+stuMin.get().getAge());
}
}
// count
// 统计功能,一般都是结合filter使用,因为先筛选出我们需要的再统计即可。及早求值
public static void count() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 22, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
long count = students.stream().filter(s1 -> s1.getAge() < 45).count();
System.out.println("年龄小于45岁的人数是:" + count);
Long num = Stream.of(
new Student("a",1,10),
new Student("b", 2,20),
new Student("aa",3,30)
).collect(Collectors.toList()).stream().map(aa-> aa.getAge()>0).count();
Consumer c = System.out::println;
c.accept("自测计算符合判断的数量:"+num);
}
// reduce 操作可以实现从一组值中生成一个值。在上述例子中用到的 count 、 min 和 max 方法,
// 因为常用而被纳入标准库中。事实上,这些方法都是 reduce 操作。及早求值。
public static void reduce() {
Integer reduce = Stream.of(1, 2, 3, 4).reduce(0, (acc, x) -> acc+ x);
System.out.println(reduce);
Consumer c = System.out::println;
Integer a = Stream.of(1,2,3,4,5,6,7).reduce(100, (aa,b) -> aa-b);
c.accept("测试加法:"+a);
}
static class OutstandingClass {
private String className;
private List<Student> list;
public OutstandingClass(String className,List<Student> list) {
this.className = className;
this.list = list;
}
public OutstandingClass() {
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public List<Student> getList() {
return list;
}
public void setList(List<Student> list) {
this.list = list;
}
}
/*********************************高级集合类及收集器******************************/
// 收集器,一种通用的、从流生成复杂值的结构。只要将它传给 collect 方法,所有
// 的流就都可以使用它了。标准类库已经提供了一些有用的收集器,以下示例代码中的收集器都是从
// java.util.stream.Collectors 类中静态导入的。
public static void CollectorsTest() {
List<Student> students1 = new ArrayList<>(3);
students1.add(new Student("路飞", 23, 175));
students1.add(new Student("红发", 40, 180));
students1.add(new Student("白胡子", 50, 185));
OutstandingClass ostClass1 = new OutstandingClass("一班", students1);
//复制students1,并移除一个学生
List<Student> students2 = new ArrayList<>(students1);
students2.remove(1);
OutstandingClass ostClass2 = new OutstandingClass("二班", students2);
//将ostClass1、ostClass2转换为Stream
Stream<OutstandingClass> classStream = Stream.of(ostClass1, ostClass2);
OutstandingClass outstandingClass = biggestGroup(classStream);
System.out.println("人数最多的班级是:" + outstandingClass.getClass());
System.out.println("一班平均年龄是:" + averageNumberOfStudent(students1));
}
/**
* 获取人数最多的班级
*/
private static OutstandingClass biggestGroup(Stream<OutstandingClass> outstandingClasses) {
return outstandingClasses.collect(
maxBy(comparing(ostClass -> ostClass.getList().size())))
.orElseGet(OutstandingClass::new);
}
/**
* 计算平均年龄
*/
private static double averageNumberOfStudent(List<Student> students) {
return students.stream().collect(averagingInt(Student::getAge));
}
// 转换成块
// 常用的流操作是将其分解成两个集合,
// Collectors.partitioningBy帮我们实现了,接收一个Predicate函数式接口
// 将示例学生分为会唱歌与不会唱歌的两个集合
public static void PartitioningByTest(String[] args) {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 23, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
// Map<Boolean, List<Student>> listMap = students.stream().collect(
// Collectors.partitioningBy(student ->
// student.getSpecialities().
// contains(SpecialityEnum.SING)));
}
// 根据学生第一个特长进行分组
// 数据分组是一种更自然的分割数据操作,
// 与将数据分成 ture 和 false 两部分不同,可以使用任意值对数据分组。Collectors.groupingBy接收一个Function做转换。
// Collectors.groupingBy与SQL 中的 group by 操作是一样的。
public static void GroupingByTest() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 23, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
// Map<SpecialityEnum, List<Student>> listMap =
// students.stream().collect(
// Collectors.groupingBy(student -> student.getSpecialities().get(0)));
}
// 字符串拼接
// 如果将所有学生的名字拼接起来,怎么做呢?通常只能创建一个StringBuilder,
// 循环拼接。使用Stream,使用Collectors.joining()简单容易。
public static void JoiningTest() {
List<Student> students = new ArrayList<>(3);
students.add(new Student("路飞", 22, 175));
students.add(new Student("红发", 40, 180));
students.add(new Student("白胡子", 50, 185));
String names = students.stream()
.map(Student::getName).collect(Collectors.joining(",","[","]"));
System.out.println(names);
List<Student> ss = Stream.of(
new Student("a", 1, 1),
new Student("b", 2, 2),
new Student("c", 3, 3)
).collect(Collectors.toList());
Consumer c = System.out::println;
String name = ss.stream().map(n -> n.getName()).collect(Collectors.joining("-","{","}"));
c.accept("测试拼接:"+name);
}
}