JDK8新特性的小用

package test.java8;

import org.junit.Test;

import java.lang.reflect.Method;
import java.time.*;
import java.time.format.DateTimeFormatter;

import java.time.temporal.TemporalAdjusters;
import java.util.*;

import java.util.function.*;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

public class Lambda {

    @Test
    public void testBaseFunction() {
        //基本语法 ,(参数)-> return {方法体};
        //消费,供给,函数,断言型
        Consumer m = x -> System.out.println(x);
        m.accept("a");
        Supplier supplier = () -> LocalDateTime.now().getDayOfMonth();
        System.out.println(supplier.get());
        Function<String, String> function = y -> y;
        System.out.println(function.apply("aa"));
        List<String> list = Arrays.asList("a", "sa", "s1", "daws");
        List<String> list1 = filterString(list, x -> x.contains("a"));
        list1.forEach(System.out::println);
        BiPredicate predicate = (x, y) -> x.equals(y);
        boolean test = predicate.test("a", "xc");
        System.out.println(test);

    }

    //自定义过滤器
    private List<String> filterString(List<String> list, Predicate<String> predicate) {
        List<String> objects = list.stream().map(x -> {
            if (predicate.test(x)) {
                //满足条件直接返回,不满足条件返回一句话
                return x;
            }
            return "字符串不包含a呀";
        }).collect(Collectors.toList());
        return objects;
    }

    @Test
    public void testStream() {
        //自定义多个学生的老师
        List<Student> students = Arrays.asList(new Student(1, "张三", "男", Arrays.asList(new Teacher(1, "英语老师", "英语"), new Teacher(2, "德育老师", "德育")))
                , new Student(2, "李四", "男", Arrays.asList(new Teacher(1, "英语老师", "英语"), new Teacher(3, "数学老师", "数学")))
                , new Student(3, "王五", "女", Arrays.asList(new Teacher(1, "英语老师", "英语"), new Teacher(2, "德育老师", "德育"), new Teacher(3, "数学老师", "数学")))
                , new Student(4, "赵六", "女", Arrays.asList(new Teacher(1, "英语老师", "英语"), new Teacher(2, "德育老师", "德育"), new Teacher(3, "数学老师", "数学"), new Teacher(4, "化学老师", "数学")))
                , new Student(5, "田七", "女", Arrays.asList(new Teacher(1, "英语老师", "英语")))
        );

        //(三种引用)类方法引用,静态方法引用,实例方法引用
        students.stream().map(Student::getId).sorted(Integer::compare).forEach(System.out::println);

        //判断所有学生的老师是否都有叫英语老师的,全部满足则返回true
        boolean ytest = students.stream().allMatch(e -> e.getTeacher().stream().anyMatch(m -> m.getName().equals("英语老师")));
        System.out.println(ytest);
        //判断是否有学号是6的学生,没有一个是6则返回true
        boolean b = students.stream().noneMatch(e -> e.getId() == 6);
        //输出所有学生和他老师
        students.stream().forEach(e -> System.out.println(e.getName() + "和他的老师" + e.getTeacher()));

        //对所有学生的学号+10然后输出
        students.stream().map(e -> {
            e.setId(e.getId() + 10);
            return e;
        }).collect(Collectors.toList()).forEach(System.out::println);

        //输出所有学号大于12
        students.stream().filter(e -> e.getId() > 13).collect(Collectors.toList()).forEach(System.out::println);

        //输出有3个及以上的学生名及其老师的数量
        students.stream().filter(e -> e.getTeacher().stream().count() >= 3).map(e -> e.getName() + "老师的数量" + e.getTeacher().size()).forEach(System.out::println);
        students.stream().flatMap(e -> Arrays.stream(e.getName().split(""))).skip(2).collect(Collectors.toList()).forEach(System.out::println);

        //輸出id最大的學生名
        Optional<String> s = students.stream().max((e, y) -> e.getId().compareTo(y.getId())).map(e -> e.getName());
        System.out.println(s.get());

        //计算学生的序号和,带默认值所以不可能为空
        Integer reduce = students.stream().map(e -> e.getId()).reduce(0, (e, y) -> Integer.sum(y.intValue(), e.intValue()));
        System.out.println(reduce);

        //计算学生的序号和,可能为空
        Optional<Integer> reduce1 = students.stream().map(e -> e.getId()).reduce((e, y) -> Integer.sum(y.intValue(), e.intValue()));
        System.out.println(reduce1.get());

        //按学号进行倒叙排序
        students.stream().sorted((e, m) -> m.getId().compareTo(e.getId())).forEach(System.out::println);

        //流的计算
        IntSummaryStatistics collect = students.stream().collect(Collectors.summarizingInt(Student::getId));
        System.out.println(collect.getMax() + " " + collect.getMin() + " " + collect.getSum());

        //打印0-100的值
        LongStream.rangeClosed(0, 100).forEach(System.out::println);
    }

    @Test
    public void testForkJoin() {
        //测试forkjoin
        List<Integer> integers = Arrays.asList(1, 32, 4, 4, 23, 2, 23);
        //串行化
        integers.stream().sequential().forEach(System.out::println);
        //并行化,底层使用forkjoin框架
        integers.stream().parallel().forEach(System.out::println);
        //forkjoin框架,讲一个大任务拆分成很多小任务,再将小任务的结果汇总成真正的结果。
        //核心,工作窃取模式 当某个线程处理完了自己线程任务时会拿其他线程的任务(双向队列)拿末尾的任务进行执行,
        // 相较于传统的多线程更能利用资源, 例 徒弟请师傅吃饭,师傅的活做完了帮徒弟做点活(为了让自己早点吃饭)。
        //实现forkjoin框架即继承RecursiveTask并实现compute方法即可。
        //新增 接口默认方法和静态方法,对于默认方法来说 类优先原则,如果实现了两个接口均含有相同名字的方法,则需要指定覆盖的方法
        //重复注解和参数注解
    }

    @Test
    public  void testTime(){
        LocalDateTime now = LocalDateTime.now();
        LocalDate now1 = LocalDate.now();
        LocalTime now2 = LocalTime.now();

        Instant now3 = Instant.now();
        //1970到现在的s数值
        long epochSecond = now3.getEpochSecond();
        System.out.println(epochSecond);

        //算11天前
        LocalDateTime localDateTime = now.plusDays(-11);
        System.out.println(localDateTime);

        LocalDateTime date1 = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        System.out.println(date1);
        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Duration 时间比较 Period 日期比较
        Duration between = Duration.between(now3,Instant.now());
        System.out.println(between.getSeconds());
        System.out.println(Period.between(now1,now1.plusDays(22)).getDays());


        // 使用自定义的日期格式格式化字符串
        DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //自定义一个日期格式
        String time = now.format(timeFormat);
        System.out.println(time);
        LocalDateTime localDateTime1 =LocalDateTime.parse(time,timeFormat);
        System.out.println(localDateTime1);



    }



    @Test
    public void testMyAnnotation1() throws NoSuchMethodException {
        //留下一个疑惑方法注解是可以打印的,但是类型注解无法打印 运行结果 2 aa bb
        Class<Lambda> lambdaClass = Lambda.class;
        Method testMyAnnotation = lambdaClass.getMethod("testMyAnnotation", String.class);
        MyAnnotation[] declaredAnnotationsByType = testMyAnnotation.getDeclaredAnnotationsByType(MyAnnotation.class);
        System.out.println(declaredAnnotationsByType.length);
        for (MyAnnotation m :
                declaredAnnotationsByType) {
            System.out.println(m.value());
        }
    }

    @MyAnnotation("aa")
    @MyAnnotation("bb")
    public void testMyAnnotation(@MyAnnotation("aaa") String s) {
    }
}

依赖

package test.java8;


import java.lang.annotation.*;

import static java.lang.annotation.ElementType.*;

@Repeatable(MyAnnotations.class)
@Target({TYPE, FIELD, METHOD,PARAMETER,CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER})
@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotation {
    String value() default "dasdas";
}

package test.java8;

import test.java8.MyAnnotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotations {
    MyAnnotation[] value();
}

package test.java8;

import java.util.List;


public class Student {

    private Integer id;
    private String name;

    public List<Teacher> getTeacher() {
        return teacher;
    }

    public Student(Integer id, String name, String sex, List<Teacher> teacher) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.teacher = teacher;
    }

    public void setTeacher(List<Teacher> teacher) {
        this.teacher = teacher;
    }

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


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }



    private String sex;
    protected List<Teacher> teacher;
}

总结:还是挺好用的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值