java8新特性实操

一、Interface

  1. default修饰的方法,是普通实例方法,可以用this调用,可以被子类继承、重写。
  2. static修饰的方法,使用上和一般类静态方法一样。但它不能被子类继承,只能用Interface调用。
public interface Interface1 {
    void f();
    default void f1(){
        System.out.println("这是Interface1中的f1()");
    };
    static void f2(){
        System.out.println("这是Interface1中static的f2()");
    }
}

public interface Interface2 {
    default void f1(){
        System.out.println("这是Interface1中的f1()");
    }
}

public class InterfaceImpl implements Interface1,Interface2{
    @Override
    public void f() {
        System.out.println("InterfaceImpl重写f()方法");
    }
    @Override
    public void f1() {
        Interface2.super.f1();
    }
    public static void main(String[] args) {
        InterfaceImpl anInterface = new InterfaceImpl();
        anInterface.f();//InterfaceImpl重写f()方法
        anInterface.f1();//这是Interface1中的f1()
        Interface1.f2();//这是Interface1中static的f2()
    }
}







二、Lambda 表达式

1.替代匿名内部类
		//1.Runnable接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("这是传统方法new Runnable()");
            }
        }).start();
        new Thread(()-> System.out.println("这是Lamabda方法new Runnable()")).start();
        //等价于
        Runnable runnable = () -> System.out.println();
        new Thread(runnable).start();


        //2.Compactor接口
        List<Integer> list = Arrays.asList(1, 2, 3, 8, 5);
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        Collections.sort(list,(o1,o2)->o1-o2);
        //等价于
        Comparator<Integer> comparator = (o1, o2) -> o1 - o2;
        Collections.sort(list,comparator);


        //3.Listener接口
        JButton jButton = new JButton();
        jButton.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                e.getItem();
            }
        });
        jButton.addItemListener(e->e.getItem());
2.自定义函数式接口
@FunctionalInterface
public interface LamabdaInterface {
    void f1(Integer i);
}
class LamabdaInterfaceDemo{
    static void f1(Integer num,LamabdaInterface lamabdaInterface){
        lamabdaInterface.f1(num);
    }
    public static void main(String[] args) {
        LamabdaInterfaceDemo.f1(2, num -> System.out.println("这是用来测试函数式接口"+num));
    }
}
3.集合迭代
		//传统foreach
        List<Integer> list = Arrays.asList(1, 2, 3, 4);
        for(Integer num : list){
            System.out.println(num);
        }
        //lamabda foreach
        list.forEach(item-> System.out.println(item));
        //or
        list.forEach(System.out::println);
        //map
        HashMap<String, String> map = new HashMap<>();
        map.put("k1","v1");
        map.put("k2","v2");
        map.forEach((k,v)-> System.out.println(v));
4.方法引用
public class Base {
    LamabdaInterface superf(){
        return null;
    }
}
class Son extends Base{
    public LamabdaInterface f(){
        return null;
    }
    public static LamabdaInterface staticf(){
        return null;
    }
    void deal(){
        //1.静态方法调用
        AbstractWrapper.DoSomething staticf = Son::staticf;
        //2.实例方法调用
        AbstractWrapper.DoSomething f = new Son()::f;
        //3.父类方法调用
        AbstractWrapper.DoSomething superf = super::superf;
        //4.构造函数调用
        AbstractWrapper.DoSomething aNew = Son::new;
    }
}







三、stream

       List<String> list = Arrays.asList("1","2","3");
        //1.符合条件的流
        Stream<String> stringStream = list.stream().filter(item -> item.equals("1") || item.equals("2"));
        stringStream.forEach(System.out::print);
        //2.流中元素的个数
        long count = list.stream().count();
        System.out.println(count);
        //3.foreach 遍历打印
        list.stream().forEach(System.out::print);
        //4.limit 获取指定元素个数的流
        Stream<String> limit = list.stream().limit(2);
        limit.forEach(System.out::print);
        //5.toArray 流转换成数组
        String[] strings = list.stream().toArray(String[]::new);
        Arrays.stream(strings).forEach(System.out::print);
        //6.map 对每个元素操作并返回新的流
        Stream<String> stringStream1 = list.stream().map(item -> item + "--");
        //7.sort 排序并打印
        stringStream1.sorted().forEach(System.out::print);

        //8.collect 将符合的元素放到容器中
        List<String> collect = list.stream().filter(item -> "1".equals(item) || "2".equals(item)).collect(Collectors.toList());
        collect.forEach(System.out::print);
        //9.List 转换成 String 逗号分割
        String collect1 = list.stream().collect(Collectors.joining(","));
        System.out.println(collect1);


        //10.对数组进行统计
        IntSummaryStatistics statistics = list.stream().mapToInt(item -> Integer.parseInt(item)).summaryStatistics();
        System.out.println("最大值:"+statistics.getMax());
        System.out.println("最小值:"+statistics.getMin());
        System.out.println("平均值:"+statistics.getAverage());
        System.out.println("总和:"+statistics.getSum());

        //11.合并流
        Stream<String> concat = Stream.concat(Arrays.asList("1", "2", "3").stream(), Arrays.asList("4", "5", "6").stream());
        concat.forEach(System.out::print);
        //12.一个流只能使用一次
        Stream<String> stream = list.stream();
        stream.limit(2);//不能再stream.foreach()
        list.stream().forEach(System.out::print);//可以这样处理

补充

public class StreamExercise {
    public static void main(String[] args) {
        //1.对map集合的操作
        HashMap<String, String> map = new HashMap<>();
        map.put("k1","1");
        map.put("k2","2");
        map.put("k3","3");
        //1.1 map 集合中key为 k1 或 k2 value总和 :
        int sum = map.entrySet().stream()
                .filter(entry -> "k1".equals(entry.getKey()) || "k2".equals(entry.getKey()))
                .mapToInt(entry -> Integer.parseInt(entry.getValue())).sum();
        System.out.println(sum);
        //1.2合并两个map key相同的进行相加
        HashMap<String, Integer> map2 = new HashMap<>();
        map2.put("k1",1);
        map2.put("k2",2);
        map2.put("k3",3);
        HashMap<String, Integer> map3 = new HashMap<>();
        map3.put("k1",1);
        map3.put("k2",2);
        map3.put("k3",3);
        map2.forEach((key,value)->map3.merge(key,value,Integer::sum));//map2合并到map3中 key相同的进行相加
        System.out.println(map3);


        //2.对list集合的操作
        List<Data> list = new ArrayList<>();
        list.add(new Data(LocalDate.now().plusDays(0)));
        list.add(new Data(LocalDate.now().plusDays(1)));
        list.add(new Data(LocalDate.now().plusDays(2)));
        //2.1根据时间对list集合元素进行升序排列
        List<Data> collect = list.stream().sorted(Comparator.comparing(Data::getLocalDate)).collect(Collectors.toList());
        collect.forEach(System.out::println);
        //2.2根据时间筛选数据
        List<Data> collect1 = list.stream().filter(item ->
                (item.getLocalDate().isAfter(LocalDate.MIN) && item.getLocalDate().isBefore(LocalDate.MAX)))
                .collect(Collectors.toList());
        collect1.forEach(System.out::println);
        //2.3对list根据某一属性进行过滤,创建新的对象组成新的集合
        List<Map<String, String>> collect2 = list.stream().filter(item -> item.getLocalDate().isAfter(LocalDate.MIN))
                .map(item -> {
                    Map<String, String> entity = new HashMap<>();
                    entity.put(item.toString(), item.getLocalDate().toString());
                    return entity;
                }).distinct().collect(Collectors.toList());
        System.out.println(collect2);
        //2.4对list集合使用分页查询
        List<Data> collect3 = list.stream().skip(1).limit(1).collect(Collectors.toList());
        System.out.println(collect3);
        //2.5对list集合中对象属性为字符串的数值进行排序
        ArrayList<Num> list1 = new ArrayList<>();
        list1.add(new Num("1"));
        list1.add(new Num("2"));
        list1.add(new Num("3"));
        List<Integer> collect5 = list1.stream().map(item -> Integer.parseInt(item.getNum())).sorted(Comparator.comparing(Integer::intValue)).collect(Collectors.toList());
        System.out.println(collect5);
        //2.6取多个list的交集
        List<Data> collect4 = list.stream().filter(list::contains).filter(list1::contains).collect(Collectors.toList());
        System.out.println(collect4);
        //2.7根据对象某一字段组成新的集合
        List<LocalDate> collect6 = list.stream().filter(item->item.getLocalDate()!=null).map(item -> item.getLocalDate()).distinct().collect(Collectors.toList());
        System.out.println(collect6);
        //2.8求list集合中某一属性的和
        int sum1 = list1.stream().mapToInt(item -> Integer.parseInt(item.getNum())).sum();
        //2.9按照list对象中某一属性进行分组
        Map<LocalDate, List<Data>> collect7 = list.stream().collect(Collectors.groupingBy(Data::getLocalDate));
        System.out.println(collect7);
    }
}
class Num{
    private String num;
    public Num(String num){
        this.num = num;
    }

    public String getNum() {
        return num;
    }
}
class Data{
    private LocalDate localDate;
    public Data(LocalDate localDate){
        this.localDate  = localDate;
    }
    public LocalDate getLocalDate() {
        return localDate;
    }
    @Override
    public String toString() {
        return "Data{" +
                "localDate=" + localDate +
                '}';
    }
}
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值