当前位置: 首页 > article >正文

Java8新特性

文章目录

    • 1.接口中默认方法修饰为普通方法
    • 2.lambda表达式
      • 如何定义函数接口
      • 无参
      • 有参
      • 精简代码
      • 实现集合遍历
      • 实现集合排序
      • 实现线程调用
    • 3.Stream流
      • strean将list转为set
      • stream将list转为map
      • stream计算求和
      • stream查找最大和最小
      • stream中的match
      • stream过滤器
      • stream实现limit
      • stream实现数据排序

1.接口中默认方法修饰为普通方法
2.lambda表达式
3.Stream流接口
4.函数式接口
5.方法与构造函数引用

1.接口中默认方法修饰为普通方法

在jdk8之前,interface之中可以定义变量和方法,变量必须是public、static、final的,方法必须是public、abstract的,由于这些修饰符都是默认的。

接口定义方法:public抽象方法 需要子类实现
接口定义变量:public、static、final

在jdk1.8开始 支持使用static和default修饰 可以写方法体,不需要子类重写
普通方法 可以有方法体
抽象方法 没有方法体需要子类实现 重写

package com.xd;

public interface JDK8Interface {
    /**
     * 默认的时候就是为public、abstract
     */
    void add();

    /**
     * jdk8 提供默认的方法
     */
    default void defaultGet(){
        System.out.println("defaultGet");
    }

    static void staticDel() {
        System.out.println("staticDel");
    }


}

package com.xd;

public class JDK8InterfaceImpl implements JDK8Interface{


    /**
     * 定义子类实现JDK8Interface 没有强制要求重写default和静态方法
     */
    @Override
    public void add() {
        System.out.println("add");
    }


}

package com.xd;

public class Test01 {
    public static void main(String[] args) {
        JDK8InterfaceImpl jdk8Interface = new JDK8InterfaceImpl();
        jdk8Interface.defaultGet();
        jdk8Interface.add();
        JDK8Interface.staticDel();
    }
}

2.lambda表达式

package com.xd;

public class Test02 {
    public static void main(String[] args) {
        //1.使用匿名内部类的形式调用OrderService中的get方法
//        OrderService orderService = new OrderService() {
//            @Override
//            public void get() {
//                System.out.println("get");
//            }
//        };
//        orderService.get();


//        new OrderService() {
//            @Override
//            public void get() {
//                System.out.println("get");
//            }
//        }.get();

//        new OrderService() {
//            @Override
//            public void get() {
//                System.out.println("get");
//            }
//        }.get();

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName()+",run");
//            }
//        }).start();











    }
}

什么是lambda表达式
lambda好处:简化匿名内部类的使用
lambda+方法引入 使代码变得更加精简

Java中的lambda表达式的规范,必须是函数接口
函数接口的定义:在该接口中只能存在一个抽象方法,该接口称为函数接口
在函数接口中可以定义object类中方法
在函数接口中可以使用默认或静态方法
@FunctionalInterface标识该接口为函数接口

如何定义函数接口

package com.xd;

@FunctionalInterface
public interface MyFunctionalInterface {
    void get();

    default void defaultAdd(){
        System.out.println("默认方法");
    }


    /**
     * object父类中的方法可以在函数接口中重写
     * @return
     */
    String toString();

}

无参

package com.xd;


@FunctionalInterface
public interface NoArgsInterface {
    void get();
}

package com.xd;



public class Test03 {
    public static void main(String[] args) {
        //1.使用匿名内部类调用
        new NoArgsInterface() {
            @Override
            public void get() {
                System.out.println("get");
            }
        }.get();

        NoArgsInterface noArgsInterface = ()->{
            System.out.println("使用lambda表达式调用方法");
        };
        noArgsInterface.get();

    }
}

有参

package com.xd;

@FunctionalInterface
public interface HasArgsInterface {

    String get(int i, int j);

}

package com.xd;

public class Test04 {
    public static void main(String[] args) {
        //1.使用匿名内部类调用
        HasArgsInterface hasArgsInterface = new HasArgsInterface() {
            @Override
            public String get(int i, int j) {
                return i + "---" + j;
            }
        };

        System.out.println(hasArgsInterface.get(1,2));
        //2.使用lambda调用有参函数方法
        HasArgsInterface hasArgsInterface1 = (i,j) -> {
            return i + "---" + j;
        };
        System.out.println(hasArgsInterface1.get(1,1));


    }
}

精简代码

package com.xd;

public class Test05 {
    public static void main(String[] args) {
        NoArgsInterface noArgsInterface = () -> {
            System.out.println("方法");

        };
        noArgsInterface.get();

        // 精简代码
        ((NoArgsInterface) () -> {
            System.out.println("方法");
        }).get();

        // 使用lambda 方法体中只有一条语句的情况下,可以不需要写{} 也可以不需要写return
        NoArgsInterface noArgsInterface1 = () -> System.out.println("方法");


        HasArgsInterface hasArgsInterface = (i, j) -> {
            return i + "-" + j;
        };
        HasArgsInterface hasArgsInterface1 = (i, j) -> i + "-" + j;

        String s = ((HasArgsInterface)(i, j) -> i + "-" + j).get(1,2);
        System.out.println(s);








    }
}

实现集合遍历

package com.xd;

import java.util.ArrayList;
import java.util.function.Consumer;

public class Test06 {
    public static void main(String[] args) {
        ArrayList<String> strings = new ArrayList<>();
        strings.add("1");
        strings.add("2");
        strings.add("3");
        strings.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        });

        strings.forEach(s -> {
            System.out.println(s);
        });


    }
}

实现集合排序

package com.xd.entity;

public class UserEntity {
    private String userName;


    public UserEntity(String userName, int age) {
        this.userName = userName;
        this.age = age;
    }

    private int age;

    public String getUserName() {
        return userName;
    }

    public int getAge() {
        return age;
    }


    @Override
    public String toString() {
        return "UserEntity{" +
                "userName='" + userName + '\'' +
                ", age=" + age +
                '}';
    }
    
    public boolean equals(Object obj){
        if (obj instanceof UserEntity)
            return userName.equals(((UserEntity) obj).userName) && age == (((UserEntity) obj).age);
        else 
            return false;
    }

    public int hashCode() {
        return userName.hashCode();
    }


}

package com.xd;

import com.xd.entity.UserEntity;

import java.util.ArrayList;
import java.util.Comparator;

public class Test07 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userLists = new ArrayList<>();
        userLists.add(new UserEntity("a",1));
        userLists.add(new UserEntity("b",4));
        userLists.add(new UserEntity("c",3));
        userLists.sort(new Comparator<UserEntity>() {
            @Override
            public int compare(UserEntity o1, UserEntity o2) {
                return o1.getAge()- o2.getAge();
            }
        });
        userLists.sort((o1,o2)->o1.getAge() - o2.getAge());
        userLists.forEach((t)->{
            System.out.println(t.toString());
        });

    }
}

实现线程调用

package com.xd;

public class Test08 {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("获取到线程名称:"+Thread.currentThread().getName()+",子线程");
            }
        }).start();


        new Thread(() -> System.out.println("获取到线程名称:"+Thread.currentThread().getName()+",子线程")).start();        
        
        
    }
}

3.Stream流

Stream:非常方便精简的形式遍历集合实现 过滤、排序等。

strean将list转为set

package com.xd.stream;

import com.xd.entity.UserEntity;

import java.util.ArrayList;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test01 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("a",1));
        userEntities.add(new UserEntity("b",4));
        userEntities.add(new UserEntity("c",3));
        userEntities.add(new UserEntity("c",3));
        userEntities.add(new UserEntity("d",3));
        userEntities.add(new UserEntity("d",1));
        /**
         * 创建stream方式两种
         * 1.串行流stream() 单线程
         * 2.并行流parallelStream() 多线程
         * 并行流parallelStream() 比 串行流stream()效率要高
         */
        Stream<UserEntity> stream = userEntities.stream();
        // 转换成set集合
        Set<UserEntity> setUserList = stream.collect(Collectors.toSet());
        setUserList.forEach(userEntity -> {
            System.out.println(userEntity.toString());
        });



    }
}

set集合底层是依赖于map集合实现防重复key map集合底层基于equals比较防重复,equals结合hashcode

stream将list转为map

package com.xd.stream;

import com.xd.entity.UserEntity;

import java.util.ArrayList;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test02 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("a", 1));
        userEntities.add(new UserEntity("b", 4));
        userEntities.add(new UserEntity("c", 3));
//        userEntities.add(new UserEntity("c", 3));
        userEntities.add(new UserEntity("d", 3));
//        userEntities.add(new UserEntity("d", 1));

        //list集合只有元素值 key list转换成map集合的情况下 指定key--user对象 username属性 value user对象
        /**
         * map<String(userName),UserEntity>
         */
        Stream<UserEntity> stream = userEntities.stream();

        /**
         * new Function<UserEntity(List集合中的类型), String(key map)>
         */
        Map<String, UserEntity> collect = stream.collect(Collectors.toMap(new Function<UserEntity, String>() {
                                                                              @Override
                                                                              public String apply(UserEntity userEntity) {
                                                                                  return userEntity.getUserName();
                                                                              }
                                                                          }, new Function<UserEntity, UserEntity>() {
                                                                              @Override
                                                                              public UserEntity apply(UserEntity userEntity) {
                                                                                  return userEntity;
                                                                              }
                                                                          }
        ));
        collect.forEach(new BiConsumer<String, UserEntity>() {
            @Override
            public void accept(String s, UserEntity userEntity) {
                System.out.println(s + "," + userEntity);
            }
        });


    }
}

stream计算求和

package com.xd;

import com.xd.entity.UserEntity;

import java.util.ArrayList;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Stream;

public class Test10 {
    public static void main(String[] args) {
//        Stream<Integer> integerStream = Stream.of(10, 9, 6, 33);
//        Optional<Integer> reduce = integerStream.reduce(new BinaryOperator<Integer>() {
//            @Override
//            public Integer apply(Integer a1, Integer a2) {
//                return a1 + a2;
//            }
//        });
//        System.out.println(reduce.get());

        ArrayList<UserEntity> userLists = new ArrayList<>();
        userLists.add(new UserEntity("a",1));
        userLists.add(new UserEntity("b",4));
        userLists.add(new UserEntity("c",3));
        Stream<UserEntity> stream = userLists.stream();
        Optional<UserEntity> sum = stream.reduce(new BinaryOperator<UserEntity>() {
            @Override
            public UserEntity apply(UserEntity user1, UserEntity user2) {
                UserEntity userEntity = new UserEntity("sum", user1.getAge() + user2.getAge());
                return userEntity;
            }
        });
        System.out.println(sum.get().getAge());


    }
}

stream查找最大和最小

package com.xd;

import com.xd.entity.UserEntity;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Stream;

public class Test11 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userLists = new ArrayList<>();
        userLists.add(new UserEntity("a",1));
        userLists.add(new UserEntity("b",4));
        userLists.add(new UserEntity("c",3));
        Stream<UserEntity> stream = userLists.stream();
        Optional<UserEntity> max = stream.max(new Comparator<UserEntity>() {
            @Override
            public int compare(UserEntity o1, UserEntity o2) {
                return o1.getAge() - o2.getAge();
            }
        });
        System.out.println(max.get());


    }
}

stream中的match

package com.xd;

import com.xd.entity.UserEntity;

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class Test12 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userLists = new ArrayList<>();
        userLists.add(new UserEntity("a",1));
        userLists.add(new UserEntity("b",4));
        userLists.add(new UserEntity("c",3));
        Stream<UserEntity> stream = userLists.stream();
        boolean b = stream.anyMatch(new Predicate<UserEntity>() {
            @Override
            public boolean test(UserEntity userEntity) {
                return "a".equals(userEntity.getUserName());
            }
        });
        System.out.println(b);
    }
}

stream过滤器

package com.xd;

import com.xd.entity.UserEntity;

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class Test13 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userLists = new ArrayList<>();
        userLists.add(new UserEntity("a",100));
        userLists.add(new UserEntity("a",200));
        userLists.add(new UserEntity("a",1));
        userLists.add(new UserEntity("b",4));
        userLists.add(new UserEntity("c",3));
        Stream<UserEntity> stream = userLists.stream();
        stream.filter(new Predicate<UserEntity>() {
            @Override
            public boolean test(UserEntity userEntity) {
                return "a".equals(userEntity.getUserName())&&userEntity.getAge() > 18;
            }
        }).forEach(userEntity -> System.out.println(userEntity));

    }
}

stream实现limit

package com.xd;

import com.xd.entity.UserEntity;

import java.util.ArrayList;
import java.util.stream.Stream;

public class Test14 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userLists = new ArrayList<>();
        userLists.add(new UserEntity("a",100));
        userLists.add(new UserEntity("a",200));
        userLists.add(new UserEntity("a",1));
        userLists.add(new UserEntity("b",4));
        userLists.add(new UserEntity("c",3));

        Stream<UserEntity> stream = userLists.stream();
        // 相当于mysql limit(0,2)
        //stream.limit(2).forEach((userEntity -> System.out.println(userEntity)));
        stream.skip(2).limit(3).forEach((userEntity -> System.out.println(userEntity)));

    }
}

stream实现数据排序

package com.xd.stream;

import com.xd.entity.UserEntity;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.stream.Stream;

public class Test03 {
    public static void main(String[] args) {
        ArrayList<UserEntity> userLists = new ArrayList<>();
        userLists.add(new UserEntity("a",100));
        userLists.add(new UserEntity("a",200));
        userLists.add(new UserEntity("a",1));
        userLists.add(new UserEntity("b",4));
        userLists.add(new UserEntity("c",3));
        Stream<UserEntity> stream = userLists.stream();
        stream.sorted(new Comparator<UserEntity>() {
            @Override
            public int compare(UserEntity o1, UserEntity o2) {
                return o1.getAge()- o2.getAge();
            }
        }).forEach(userEntity -> System.out.println(userEntity.toString()));


    }
}


http://www.kler.cn/a/578881.html

相关文章:

  • 【JavaSE】【IO】文件操作
  • windows部署spleeter 版本2.4.0:分离音频的人声和背景音乐
  • 【Linux】缓冲区
  • P9425 [蓝桥杯 2023 国 B] AB 路线(无结构体+取模判断+详细注释版)
  • 【Python机器学习】1.9. 逻辑回归实战(进阶):建立二阶边界模型
  • 批量合并 Word 文档,支持合并成一个 Word,也支持按文件夹合并
  • 【贪心算法】柠檬水找零
  • 6.聊天室环境安装 - Ubuntu22.04 - elasticsearch(es)的安装和使用
  • 智科 机器学习毕业设计题目指导
  • 通义万相2.1开源版本地化部署攻略,生成视频再填利器
  • MongoDB winx64 msi包安装详细教程
  • 深入剖析Android Service:原理、生命周期与实战应用
  • 点云从入门到精通技术详解100篇-基于深度学习的三维点云分类分割
  • 实战1. 利用Pytorch解决 CIFAR 数据集中的图像分类为 10 类的问题
  • Codeforces Round 305 (Div. 1) C. Mike and Foam 容斥原理、质因数分解
  • ACE协议学习1
  • 【python爬虫】酷狗音乐爬取
  • JavaWeb后端基础(7)AOP
  • 用K8S部署Milvus服务
  • 2025-3-9 leetcode刷题情况(贪心算法--序列问题)