Java8 新特性
1.Lambda表达式
a.适用范围:只有一个抽象方法的函数式接口
b.函数式接口注解:@FunctionalInterface(编译时若该接口不符合函数式接口,会提示异常)
c.使用:
1)创建函数式接口
@FunctionalInterface public interface Increase { public int increase(int num); }
2)使用
public static void main(String[] args) { //一行执行语句 Increase increase = (num) -> num + 1; System.out.println(increase.increase(1)); //多行执行语句 increase = (num) -> { num = num + 1; return num; }; System.out.println(increase.increase(3)); }
2.Stream流
a.使用
List<TestBean> beanList = new ArrayList<>(); TestBean goods = new TestBean(); goods.setCode(10); beanList.add(goods); for (int i = 20; i >= 0; i--) { goods = new TestBean(); goods.setCode(i); beanList.add(goods); } goods = null; beanList.add(goods); //流操作 List<Integer> resultList = beanList.stream() //生成流 .filter((bean) -> bean != null) //过滤 // .map((bean) -> bean.getCode()) .map(TestBean::getCode) //映射每个元素到对应的结果 .distinct() //去重 .sorted() //排序 .skip(5) //跳过5个 .limit(10) //取10个 .collect(Collectors.toList()); //将流转换成集合 //合并字符串 String resultString = resultList.stream().map((code) -> String.valueOf(code)).collect(Collectors.joining(", ")); System.out.println(resultString); //循环 // resultList.forEach((code) -> System.out.println(code)); resultList.forEach(System.out::println);
3.方法引用
a.分类:
1)构造器方法引用(Class::new)
2)类静态方法引用(Class::static_method)
3)类普通方法引用(Class::method),方法不能带参数
4)实例方法引用(instance::method)
b.使用:
public class TestBean { private int num; public int getNum() { return num; } public void setNum(int num) { this.num = num; } @Override public String toString() { return "[TestBean]num:" + num; } //-------------------------------------------------------------- public static TestBean create(Supplier<TestBean> supplier ){ return supplier.get (); } public static void updateNum(TestBean bean){ bean.setNum(1); } public void incrNum(){ this.setNum(this.getNum() + 1); } public void incrNum4Bean(TestBean bean){ bean.setNum(bean.getNum() + 1); } }
public static void main(String[] args) { List<TestBean> list = new ArrayList<>(); //构造器方法引用: Class::new,调用默认构造器 TestBean bean = TestBean.create(TestBean::new); list.add(bean); //类静态方法引用: Class::static_method list.forEach(TestBean::updateNum); System.out.println(list); //类普通方法引用: Class::method,方法不能带参数 list.forEach(TestBean::incrNum); System.out.println(list); //实例方法引用: instance::method list.forEach(new TestBean()::incrNum4Bean); System.out.println(list); }