1. 程式人生 > >Java8 lambda 的使用

Java8 lambda 的使用

摘要: 1.Java8 新特性介紹 2.專案中應用

1.Java8 新特性介紹

原文連結 https://my.oschina.net/chenxiaobian/blog/704421,https://www.cnblogs.com/hmdrzql/p/6354010.html

現在我們有一個需求:給一個user組成的list 按照user的年齡排序。實現不難,程式碼如下:

 UserCompare是一個實現了Comprator的類

這種方法由於sort方法的第二個引數是Comparator 所以你要寫一個實現類(我這裡是UserCompare類),並且override該介面的實現方法。

java8提供了lambda來簡化,有了lambda程式設計師從此不加班呀~    

剛才那個Comparator的實現類以及內部若干程式碼就都省了,代之以lambda表示式。

另外,IntelliJ會提示你改成更好的寫法

實現類裡有多少程式碼,你就省了多少行程式碼。

高興了半天,到底是什麼原理呢?其實是java8新提供的語法糖。

我們開啟java1.8 Comparator的定義,發現了類定義上面多了一個@FunctionalInterface

對,1.8多了一個概念就是FunctionalInterface,這個Comparator就是一個FunctionalInterface

有了這個註解,原來使用實現類的地方就可以代之以lambda表示式。

 

寫java的同學對java8肯定知道 那麼java8到底有哪些特性呢,總結如下:

Lambda表示式

函式式介面

Stream

Optional

Predicate

Function

Consumer

Filter

Map-Reduce

新的Date API

最核心的當然是函數語言程式設計了,寫程式碼非常簡單,請看下面詳細例子介紹

2.Java8 lambda使用總結-結合例項介紹

很多同學一開始接觸Java8可能對Java8 Lambda表示式有點陌生,下面我將結合例項介紹Java8的使用 並與Java7進行比較:

基礎類

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Person {
 
    private int id;
    private String name;
    private String address;
 
 
}

1.List操作

public class ExampleList {
    private static List<String> items = new ArrayList<>();
 
    static {
        items.add("A");
        items.add("BC");
        items.add("C");
        items.add("BD");
        items.add("E");
    }
 
    public static void main(String[] args) {
        //Java8之前操作List
        for(String item:items){
            System.out.println(item);
        }
 
        //Java8 lambda遍歷list
        items.forEach(c-> System.out.println(c));
 
        items.forEach(item->{
            if("C".equals(item)){
                System.out.println(item);
            }
        });
 
        System.out.println("--------");
 
        //先過濾
        items.stream().filter(s->s.contains("B")).forEach(c1-> System.out.println(c1));
 
    }
}

2.Map操作

public class ExampleMap {
 
    private static Map<String, Integer> items = new HashMap<>();
 
    static {
        items.put("A", 10);
        items.put("B", 20);
        items.put("C", 30);
        items.put("D", 40);
        items.put("E", 50);
        items.put("F", 60);
    }
 
    public static void main(String[] args) {
 
        //Java8之前遍歷是這樣遍歷map
        for(Map.Entry<String,Integer> entry:items.entrySet()){
            System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
        }
 
        //Java8遍歷map
        items.forEach((key,value)-> System.out.println("key:" + key + " value:" + value));
 
 
    }
 
 
}

3.Groupingby操作

/**
 * 
 *Java8 Collectors.groupingBy and Collectors.mapping example
 */
public class ExampleMapping {
 
    private static List<Person> personList = Lists.newArrayList();
 
    static {
        personList.add(Person.builder().id(10).address("apple").address("shanghai").build());
        personList.add(Person.builder().id(12).address("apple").address("wuhan").build());
        personList.add(Person.builder().id(16).address("apple").address("nanjing").build());
    }
 
    public static void main(String[] args) {
        //分組
        Map<String, List<Person>> collect = personList.stream().collect(Collectors.groupingBy(c -> c.getAddress()));
        System.out.println(collect);
    }
}

4.List轉換為Map

public class ExampleListConvertMap {
 
    private static List<Person> personList = Lists.newArrayList();
 
    static{
        personList.add(Person.builder().id(20).name("zhangsan").address("shanghai").build());
        personList.add(Person.builder().id(30).name("lisi").address("nanjing").build());
    }
 
    public static void main(String[] args) {
        //Java8 List轉換Map
        Map<Integer,Person> map_ = personList.stream().collect(Collectors.toMap((key->key.getId()),(value->value)));
        map_.forEach((key,value)-> System.out.println(key + ":" + value));
        
        Map<Integer, Person> mappedMovies = personList.stream().collect(  
            Collectors.toMap(Person::getRank, Person::getData)); 
 
    }
}

5.FilterMap操作

public class ExampleFilterMap {
 
    private static Map<Integer,String> map_ = Maps.newHashMap();
 
    static{
        map_.put(1, "linode.com");
        map_.put(2, "heroku.com");
        map_.put(3, "digitalocean.com");
        map_.put(4, "aws.amazon.com");
    }
 
    public static void main(String[] args) {
        //before java iterator map
        String result = null;
        for(Map.Entry<Integer,String> entry:map_.entrySet()){
            if("heroku.com".equals(entry.getValue())){
                result = entry.getValue();
            }
        }
 
        System.out.println("Before Java 8 :" + result);
 
        //Java8 Map->Stream->Filter->String
        result =  map_.entrySet().stream().
                filter(map->"heroku.com".equals(map.getValue()))
                .map(map->map.getValue())
                .collect(Collectors.joining());
        System.out.println("Java 8 :" + result);
 
       Map<Integer,String> collect =  map_.entrySet().stream()
                .filter(c->c.getKey()==2)
                .collect(Collectors.toMap(p->p.getKey(),p->p.getValue()));
        System.out.println(collect);
 
    }
}

6.Optional操作可以防止NullPointException

Optional<String> optional = Optional.of("hello");
System.out.println(optional.isPresent());//true
System.out.println(optional.get());//hello
System.out.println(optional.orElse("false"));
optional.ifPresent((s)-> System.out.println(s.charAt(0)));//h

7.給出一個詳細的例子

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
 
    private String name;
    private int salary;
    private String office;
}
 
 
public class ExampleEmployee {
 
    private static List<Employee> employeeList = Lists.newArrayList();
 
    static{
        employeeList.add(Employee.builder().name("Matt").salary(5000).office("New York").build());
        employeeList.add(Employee.builder().name("Steve").salary(6000).office("London").build());
        employeeList.add(Employee.builder().name("Carrie").salary(20000).office("New York").build());
        employeeList.add(Employee.builder().name("Peter").salary(7000).office("New York").build());
        employeeList.add(Employee.builder().name("Pat").salary(8000).office("London").build());
        employeeList.add(Employee.builder().name("Tammy").salary(29000).office("Shanghai").build());
    }
 
    public static void main(String[] args) {
        //anyMatch
        boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
        System.out.println(isMatch);
 
        //返回所有salary大於6000
        boolean matched = employeeList.stream().allMatch(employee -> employee.getSalary()>4000);
        System.out.println(matched);
 
        //找出工資最高
        Optional<Employee> hightestSalary = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println(hightestSalary);
 
        //返回姓名列表
        List<String> names = employeeList.stream().map(employee -> employee.getName()).collect(Collectors.toList());
        System.out.println(names);
 
        //List轉換成Map
        Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
        employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
 
        //統計辦公室是New York的個數
        long officeCount = employeeList.stream().filter(employee -> employee.getOffice().equals("Shanghai")).count();
        System.out.println(officeCount);
 
        //List轉換為Set
        Set<String> officeSet = employeeList.stream().map(employee -> employee.getOffice()).distinct().collect(Collectors.toSet());
        System.out.println(officeSet);
 
        //查詢辦公室地點是New York的員工
        Optional<Employee> allMatchedEmployees = employeeList.stream().filter(employee -> employee.getOffice().equals("New York")).findAny();
        System.out.println(allMatchedEmployees);
 
        //按照工資的降序來列出員工資訊
        List<Employee> sortEmployeeList =  employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
        //按照名字的升序列出員工資訊
        List<Employee> sortEmployeeByName = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
        System.out.println(sortEmployeeList);
        System.out.println("按照名字的升序列出員工資訊:" + sortEmployeeByName);
 
        //獲取工資最高的前2條員工資訊
        List<Employee> top2EmployeeList= employeeList.stream()
                .sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary()))
                .limit(2)
                .collect(Collectors.toList());
        System.out.println(top2EmployeeList);
 
        //獲取平均工資
        OptionalDouble averageSalary = employeeList.stream().mapToInt(employee->employee.getSalary()).average();
        System.out.println("平均工資:" + averageSalary);
 
        //查詢New York
        OptionalDouble averageSalaryByOffice = employeeList.stream().filter(employee -> employee.getOffice()
                .equals("New York"))
                .mapToInt(employee->employee.getSalary())
                .average();
        System.out.println("New York辦公室平均工資:" + averageSalaryByOffice);
 
    }
}

8.Java8常見操作

 
public class EmployeeTest {
 
    public static List<Employee> generateData() {
        return Arrays.asList(new Employee("Matt", 5000, "New York"),
                new Employee("Steve", 6000, "London"),
                new Employee("Carrie", 10000, "New York"),
                new Employee("Peter", 7000, "New York"),
                new Employee("Alec", 6000, "London"),
                new Employee("Sarah", 8000, "London"),
                new Employee("Rebecca", 4000, "New York"),
                new Employee("Pat", 20000, "New York"),
                new Employee("Tammy", 9000, "New York"),
                new Employee("Fred", 15000, "Tokyo"));
    }
 
    public static Map<String, Integer> generateMapData() {
        Map<String, Integer> items = Maps.newHashMap();
        items.put("A", 10);
        items.put("B", 20);
        items.put("C", 30);
        items.put("D", 40);
        items.put("E", 50);
        items.put("F", 60);
 
        return items;
    }
 
 
    @Test
    public void testEmployee() {
        List<Employee> results = generateData();
 
        //打印出名字是Steve的員工資訊
        results.forEach(c -> {
            if (c.getName().equals("Steve")) {
                System.out.println(c);
            }
        });
 
        System.out.println("---------");
 
        //找出年薪超過6000的員工
        results.stream().filter(c -> c.getSalary() >= 60000).forEach(c -> System.out.println(c));
 
        System.out.println("--->>>>>>----");
 
        //java8遍歷map
        Map<String, Integer> map_ = generateMapData();
        map_.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
 
        System.out.println("---->>>>分組>>>-----");
 
        //java8 分組操作
        Map<String, List<Employee>> groupMap = results.stream().collect(Collectors.groupingBy(c -> c.getOffice()));
        System.out.println(groupMap);
 
        System.out.println("---->>>>List轉化為Map>>>----");
        //List轉化Map
        Map<String, Object> map = results.stream().collect(Collectors.toMap(Employee::getName, Employee::getOffice));
        map.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
 
        System.out.println("---->>>>>>>----");
        Map<Integer, Employee> employeeMap = results.stream().collect(Collectors.toMap((key -> key.getSalary()), (value -> value)));
        employeeMap.forEach((key, value) -> System.out.println(key + "," + value));
 
        System.out.println("---->>遍歷map>>>----");
        //打印出值大於30的map
        Map<String, Integer> resultMap = map_.entrySet().stream().filter(c -> c.getValue() > 30).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
        resultMap.forEach((key, value) -> System.out.println(key + "=" + value));
 
        System.out.println(">>>>>>>>>>>>>>>");
        //列印key=D的map
        Map<String, Integer> mapResults = map_.entrySet().stream().filter(c -> c.getKey().equals("D")).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
        mapResults.forEach((key, value) -> System.out.println(key + ">>>>" + value));
 
        System.out.println(">>>>>>>Optional>>>>>>>");
        Optional<String> optional = Optional.of("hello");
        System.out.println(optional.isPresent());
 
    }
 
    @Test
    public void testEmployeeExample() {
        //anyMatch
        List<Employee> employeeList = generateData();
        boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
        System.out.println(isMatch);
 
        //allMatch
        boolean matched = employeeList.stream().allMatch(employee -> employee.getOffice().equals("London"));
        System.out.println(matched);
 
        //找出工資最高的
        Optional<Employee> employeeOptional = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println(employeeOptional);
 
        //找出工資最少的
        Optional<Employee> employee = employeeList.stream().min((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println(employee);
 
        //返回姓名列表
        List<String> names = employeeList.stream().map(c->c.getName()).collect(Collectors.toList());
        System.out.println(names);
 
        System.out.println(">>>>>>>>>>>");
        //List轉化Map
        Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
        employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
 
        //統計辦公室是New York的個數
        long officeCount =  employeeList.stream().filter(c->c.getOffice().equals("New York")).count();
        System.out.println(officeCount);
 
        long salaryCount = employeeList.stream().filter(c->c.getSalary()>60000).count();
        System.out.println(salaryCount);
 
        //List轉化為Set
        Set<String> officeSet = employeeList.stream().map(c->c.getOffice()).distinct().collect(Collectors.toSet());
        System.out.println(officeSet);
 
        Set<Integer> salarySet = employeeList.stream().map(c->c.getSalary()).distinct().collect(Collectors.toSet());
        System.out.println(salarySet);
 
        //查詢辦公室地點是New York的員工
        Optional<Employee> optionals = employeeList.stream().filter(c->c.getOffice().equals("New York")).findAny();
        System.out.println(optionals);
 
        System.out.println(">>>>>工資降序排序>>>>>");
        //按照工資的降序來列出員工資訊
        List<Employee> sortSalaryEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
        System.out.println(sortSalaryEmployeeList);
 
        System.out.println(">>>>>姓名升序排序>>>>>");
        List<Employee> sortNameEmployeeList = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
        System.out.println(sortNameEmployeeList);
 
        System.out.println(">>>>獲取工資最高的前2條員工資訊");
        List<Employee> dispaly2EmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).limit(2).collect(Collectors.toList());
        System.out.println(dispaly2EmployeeList);
 
        System.out.println(">>>>獲取平均工資");
        OptionalDouble averageSalary = employeeList.stream().mapToInt(c->c.getSalary()).average();
        System.out.println(averageSalary);
 
        System.out.println(">>>>獲取工作地點的平均工資");
        OptionalDouble optionalDouble = employeeList.stream().filter(c->c.getOffice().equals("New York")).mapToInt(c->c.getSalary()).average();
        System.out.println(optionalDouble);
 
        System.out.println(">>>>>>Java8 Optional用法>>>>>>");
        Optional<String> stringOptional = Optional.of("test");
        System.out.println(stringOptional.get());
 
        Optional<String> isOptional = Optional.ofNullable("hello");
        System.out.println(isOptional.isPresent());
        System.out.println(isOptional.get());
        System.out.println(isOptional.orElse("0"));
 
        System.out.println(">>>>>>>>>>>>");
        //Optional<String> optionalVal = Optional.of(null);
        // System.out.println(optionalVal);
        Optional<String> optional = Optional.ofNullable("optional");
        System.out.println(optional);
        System.out.println(optional.isPresent());
        System.out.println(optional.get());
        System.out.println(optional.orElse("haha"));
        System.out.println(">>>>>>>>>>>>");
 
        Optional<Employee> employeeOptional_ = employeeList.stream().filter(c->c.getOffice().equals("New York")).findFirst();
        System.out.println(employeeOptional_);
 
    }