专业编程基础技术教程

网站首页 > 基础教程 正文

java8新特性

ccvgpt 2024-08-09 11:58:10 基础教程 8 ℃

1、lambda表达式

public class lamdaTest {

    final static String message="1111";

    public static void main(String[] args) {
        //(parameters) -> expression或(parameters) ->{statements; }
        lambda();
    }

    public static  void lambda(){
        lamdaTest lamdaTest =new lamdaTest();

        //1、构建方法实现
        GreetingService greetingService1=message -> System.out.println(message);

        GreetingService greetingService2=message -> {
            System.out.println(message);
        };
        //2、方法调用
        greetingService1.sayMessage("hello");
        greetingService1.sayMessage(message);//只能使用外部被final修饰的变量

        //类型声明
        MathOperation add=(int a,int b)->a+b;
        //不用类型声明
        MathOperation sub = (a,b)->a-b;
        //大括号内返回结果
        MathOperation multip=(a,b)->{return a*b;};
        //没有大括号及返回语句
        MathOperation division= (int a,int b)->a/b;

        //3、将add函数作为参数
        System.out.println(lamdaTest.operation(2,4,add));
    }

    interface MathOperation {
        int operation(int a,int b);
    }

    interface GreetingService{
        void sayMessage(String message);
    }

    //lambda支持将函数作为一个方法的参数 (其实也是将接口对象作为参数)
    private int operation(int a,int b,MathOperation mathOperation){
        return mathOperation.operation(a,b);
    }
}

2、方法引用

public class Car {

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

    //Supplier是jdk1.8的接口,这里和lamda一起使用了
    public static Car create( Supplier<Car> supplier) {
        return supplier.get();
    }

    public static void collide( Car car) {
        System.out.println("Collided " + car.toString());
    }

    public void follow( Car another) {
        System.out.println("Following the " + another.toString());
    }

    public void repair() {
        System.out.println("Repaired " + this.toString());
    }

    public static void main(String[] args) {
        //构造器引用:它的语法是Class::new,或者更一般的Class< T >::new实例如下:
        Car car  = Car.create(Car::new);
        Car car1 = Car.create(Car::new);
        Car car2 = Car.create(Car::new);
        Car car3 = new Car();
        List<Car> cars = Arrays.asList(car,car1,car2,car3);
        System.out.println("===================构造器引用========================");
        //静态方法引用:它的语法是Class::static_method,实例如下:
        cars.forEach(Car::collide);
        System.out.println("===================静态方法引用========================");
        //特定类的任意对象的方法引用:它的语法是Class::method实例如下:
        cars.forEach(Car::repair);
        System.out.println("==============特定类的任意对象的方法引用================");
        //特定对象的方法引用:它的语法是instance::method实例如下:
        final Car police = Car.create(Car::new);
        cars.forEach(police::follow);
        System.out.println("===================特定对象的方法引用===================");

    }
}

3、函数式接口

public class InterfaceTest {
    /**
     * 函数式编程,在1.8之前,java方法的参数基本还只能是变量,对象,在1.8提出函数式编程后,可以将方法作为参数,大大提高了程序的灵活性。
     * @param args
     */
    public static void main(String[] args) {
        //function【参数,函数定义】
        String str = dealString("hello",s->s.toUpperCase());
        //supplier
        getList(10,()->new Random().nextInt(100));
        //consumer
        handleConsumer(i-> System.out.println(i),100);
        //predicate
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9);
        eval(list,n->n%2==0);
    }


    public static String dealString(String str, Function<String,String> function){
        return function.apply(str);
    }

    public static List<Integer> getList(int number, Supplier<Integer> supplier){
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<number;i++){
            list.add(supplier.get());
        }
        return list;
    }

    public static void handleConsumer(Consumer<Integer> consumer,Integer number){
        consumer.accept(number);
    }

    //推断
    public static void eval(List<Integer> list, Predicate<Integer> predicate){
        for(Integer n:list){
            if(predicate.test(n)){
                System.out.println(n+"--");
            }
        }
    }
}

4、接口默认方法

默认方法的最典型用法是逐步为接口提供附加功能,而不破坏实现类。

此外,它们还可以用来为现有的抽象方法提供额外的功能。

java8新特性

public interface MyInterface {

// 普通接口方法<br> public void ptMethod();

default void defaultMethod1() {
// 默认方法
}
}



5、stream

public class StreamTest {


    static List<Person> personList = new ArrayList<Person>();

    static List<Person> personNull = null;

    private static void initPerson() {
        personList.add(new Person("张三", 8, 3000));
        personList.add(new Person("李四", 18, 5000));
        personList.add(new Person("王五", 28, 7000));
        personList.add(new Person("孙六", 38, 9000));
    }

    public static void main(String[] args) {
        initPerson();
        //创建一个比较器
        collection();

    }

    private static void compare() {
        Comparator<? super Person> comparator = Comparator.comparingInt(Person::getAge);
        Optional<Person> optional =personList.stream().max(comparator);
        System.out.println(optional);
    }

    /**
     map: 将参数映射成一个新的元素。【对象-->元素】
     flatmap:将参数的每个值映射成一个流,最后合并成一个大流。【每个字符串拆分-->统一合并】
     */
    public static void map(){
        //map 遍历薪资
        List<Integer> persons =  personList.stream().map(x->x.getSalary()+500).collect(Collectors.toList());
        System.out.println(persons);

        //flagmap
        String[] arr = {"z, h, a, n, g", "s, a, n"};
        List<String> list = Arrays.asList(arr);

        list.stream().flatMap(x->{
           String[] arrs  = x.split(",");
           Stream<String> stream = Arrays.stream(arrs);
           return stream;
        }).collect(Collectors.toList());

        System.out.println(list);
    }


    //归约,也称缩减,顾名思义,"是把一个流缩减成一个值",能实现对集合求和、求乘积和求最值操作。
    public static void reduceTest(){
        List<Integer> list = Arrays.asList(1,2,3,5);
        //求和
        int sum = list.stream().reduce((x,y)->x+y).get();
        System.out.println("求和:"+sum);
        //求积
        int ji = list.stream().reduce((x,y)->x*y).get();
        System.out.println("求积:"+ji);
        //求最值
        int max=list.stream().reduce((x,y)->x>y?x:y).get();
        System.out.println("最大值:"+max);
    }

    /**
     计数: count
     平均值: averagingInt、 averagingLong、 averagingDouble
     最值: maxBy、 minBy
     求和: summingInt、 summingLong、 summingDouble
     统计以上所有: summarizingInt、 summarizingLong、 summarizingDoubl
     */
    public static void collection(){
            //统计员工人数
            Long count = personList.stream().collect(Collectors.counting());
            //求平均工资
            Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
            //求最高工资
            Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
            //求工资之和
            Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
            //一次性统计所有信息
            DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
            System.out.println("统计员工人数:"+count);
            System.out.println("求平均工资:"+average);
            System.out.println("求最高工资:"+max);
            System.out.println("求工资之和:"+sum);
            System.out.println("一次性统计所有信息:"+collect);
    }
}



6、Optional

public class OptionalTest {

    static List<Person> personList = new ArrayList<Person>();

    static List<Person> personNull = null;

    private static void initPerson() {
        personList.add(new Person("张三", 8, 3000));
        personList.add(new Person("李四", 18, 5000));
        personList.add(new Person("王五", 28, 7000));
        personList.add(new Person("孙六", 38, 9000));
    }

    public static void main(String[] args) {
        initPerson();
        //封装Optional对象-->操作Optional对象【非空判断、过滤、映射、规约】-->得到目标结果
        Integer totalSalary=
                Optional.ofNullable(personNull)
                .orElse(personList)
                .stream().filter(x -> x.getAge() > 20)
                .map(x -> x.getSalary())
                .reduce((x,y)->x+y)
                .get();
        System.out.println("大于20岁人的薪资总和: "+totalSalary);
    }
}



7、日期

public class DateTest {
    /**
     LocalTime 时分秒
     LocalDate 年月日
     LocalDateTime 年月日时分秒
     DateTimeFormatter 时间格式
     */
    public static void main(String[] args) {
        final LocalDate now = LocalDate.now();

        System.out.println("今天是 " + now);

        System.out.println("1970年到现在一共 " + now.toEpochDay() + " 天");

        final int lengthOfYear = now.lengthOfYear();
        System.out.println("今年一共 " + lengthOfYear + " 天");

        final int lengthOfMonth = now.lengthOfMonth();
        System.out.println("本月一共 " + lengthOfMonth + " 天");

        final boolean leapYear = now.isLeapYear();
        System.out.println("今年是否是闰年:" + leapYear);

        final LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("本月的第一天是 : " + firstDayOfMonth);

        //下一个周一
        final LocalDate withMONDAY = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        System.out.println("下周一日期是 :" + withMONDAY);

        System.out.println(" 日期在当前时间之后: " + withMONDAY.isAfter(now));
        System.out.println(" 日期在当前时间之前: " + withMONDAY.isBefore(now));

        //最后一个周一
        final LocalDate lastMONDAY = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.TUESDAY));
        System.out.println("本月最后一个周二是 :" + lastMONDAY);

        final LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("本月最后一天是 : " + lastDay);

        // 加一年
        final LocalDate plusYears = now.plusYears(1);
        System.out.println("当前日期加一年 : " + plusYears);

        //两个日期相差天数
        System.out.println("两个日期相差天数:" + (plusYears.toEpochDay() - now.toEpochDay()));

        final LocalDate plusMonths1 = now.plusMonths(12);
        System.out.println("当前日期加12 个月 :" + plusMonths1);

        final LocalDate minusDays = now.minusDays(1);
        System.out.println("当前日期减 1 天 : " + minusDays);

        final LocalDate plusDays = now.plusDays(1);
        System.out.println("当前日期加 1 天 : " + plusDays);

        final int dayOfMonth = now.getDayOfMonth();
        System.out.println("今天是这个月的第 " + dayOfMonth + " 天");
        final int monthValue = now.getMonthValue();
        System.out.println("本月是今年的第  " + monthValue + "月");
        final Month month = now.getMonth();
        System.out.println("本月的英文 : " + month);

        // 本周的周几
        final DayOfWeek dayOfWeek = now.getDayOfWeek();
        System.out.println("今天是周几英文: " + dayOfWeek);
        System.out.println("今天是本周周几: " + dayOfWeek.getValue());

        // string 转 localDate
        final LocalDate parse = LocalDate.parse("2021-07-12");
        final LocalDate parse1 = LocalDate.parse("2021-07-12", DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        System.out.println(parse1);
        System.out.println(" 转日期 " + parse);
        System.out.println("DateTimeFormatter 转日期 " + parse1);

        //获取指定日期
        final LocalDate startDate = LocalDate.of(2021, 6, 30);
        System.out.println(startDate);

        final LocalDateTime nowDateTime = LocalDateTime.now();
        System.out.println("当前日期时间:" + nowDateTime);

        final LocalTime localTime = LocalTime.now();
        System.out.println("当前时间: " + localTime);
        final String format = nowDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a"));
        System.out.println("当前日期时间 格式化" + format);
    }
}

最近发表
标签列表