java-----java8新特性介绍

var类型

//自动转换类型
var a = 100;
var b = 100.0;

Stream对象

public class App
{
    public static void main(String[] args)
    {
    	//java8新特性,除了map对象其他Collection对象可以转化为流
    	//并且可以支持filter,map等操作
        List<String> list = List.of("index1","index2","index3");
        list.stream().filter((s)->{return s.startsWith("index3");}).map((s)->{return s.replaceAll("i", "I");}).forEach((s)->System.out.println(s));

		//sort操作
		//值得注意的是可以使用list.parallelStream().sorted()执行并行排序,以优化排序速度
        list = List.of("index100","index1","index10");
        list.stream().sorted((a,b)->
        {
            return a.length() > b.length()?1:-1;
        }).forEach((s)->
        {
            System.out.println(s);
        });
    }
}

Lambda表达式

public class App
{
    public static void main(String[] args)
    {
        App app = new App();
        //如果lambda只有一行,默认返回这一行的结果,例如
        //(x)->x+1
        //(x)->{return x + 1;}等价
        app.function((x)->{System.out.println("inside lambda --- " + x);
                        return x;});
    }

	//注意Function模板必须使用包装类Integer而不是int
    void function(Function<Integer,Integer> func)
    {
        func.apply(123);
    }
}

默认接口方法

interface Formula {
    double calculate(int a);

	//实现这个接口的类,如果它没有@override这个方法,则默认实现如下
    default double sqrt(int a) {
        return Math.sqrt(a);
    }
}

方法引用&构造函数引用

//方法引用
Converter<String, Integer> converter = Integer::valueOf;
Integer converted = converter.convert("123");
System.out.println(converted);   // 123

//构造引用
public class App
{
    public static void main(String[] args)
    {
        Function<Integer,Sample> func = Sample::new;
        Sample sample = func.apply(123);
    }
}

class Sample
{
    public Sample(int a)
    {
        System.out.println("Constructer function of Sample --- " + a);
    }
}

几种内置接口

  • Predicates
  • Runnable(所有方法默认继承这个接口)
  • Functions
  • Suppliers
  • Consumers
  • Comparators
  • Optionals
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值