Java8 新特性

2019-08-16  本文已影响0人  小石头呢

一.Lambda 表达式

Android Studio中可能会出现无法使用,提示说语言等级是7无法使用,Alt+Insert调用解决方法,重新编译。

1.概念

Lambda 表达式,也可称为闭包,允许把函数作为一个方法的参数。

2.重要特征

3.Lambda表达式实例

// 1. 不需要参数,返回值为 5  
() -> 5  
  
// 2. 接收一个参数(数字类型),返回其2倍的值  
x -> 2 * x  
  
// 3. 接受2个参数(数字),并返回他们的差值  
(x, y) -> x – y  
  
// 4. 接收2个int型整数,返回他们的和  
(int x, int y) -> x + y  
  
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
(String s) -> System.out.print(s)

4.注意

5.Lambda运用实例

Collection<Integer> collectionTemp1 = new ArrayList();
collectionTemp1.add(1);
collectionTemp1.add(2);
collectionTemp1.add(3);

collectionTemp1.removeIf(obj -> obj > 2);
System.out.println(collectionTemp1);

输出:[1, 2]
public class Person {
    String name;
    int age;

    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
}

import java.util.ArrayList;

public class Test {
    public static void main(String[] args){

        ArrayList<Person> persons = new ArrayList<>();

        String[] names = {"张明","张杰","李明浩","李浩天","李隆基","李世明"};

        for (int i = 0; i < names.length; i++) {
            Person person = new Person(names[i],i+30);
            persons.add(person);
        }

        ShowTheResult.show(persons,lists -> {

            int ageCount = 0;
            int nameCount = 0;

            for (Person people : lists) {

                if (people.age > 30){
                    ageCount++;
                }

                if (people.name.contains("张")){
                    nameCount++;
                }
            }

            System.out.println("名字里面含有张的人数是:"+nameCount+" "+"年龄超过30的人数是:"+ageCount);
        });

    }
}

interface Show{
    void showTheCount(ArrayList<Person> T);
}

class ShowTheResult{
    public static void show(ArrayList<Person> T,Show s){
        s.showTheCount(T);
    }
}

二.方法引用

三.函数式接口

四.默认方法

五.Stream

六.Optional 类

七.Nashorn, JavaScript 引擎

八.新的日期时间 API

Base64

上一篇下一篇

猜你喜欢

热点阅读