java Lambda

Posted liehen2046

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Lambda相关的知识,希望对你有一定的参考价值。

源码

package com.keyba.example;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;


public class LambdaTest 
    public static void main(String[] args) 
        String[] atp = "Rafael Nadal", "Novak Djokovic", "Stanislas Wawrinka", "David Ferrer",
                "Roger Federer", "Andy Murray", "Tomas Berdych", "Juan Martin Del Potro";
        List<String> players = Arrays.asList(atp);

        // 以前的循环方式
        for (String player : players) 
            System.out.print(player + "; ");
        
        System.out.println();

        // 使用 lambda 表达式以及函数操作(functional operation)
        players.forEach((player) -> System.out.print(player + "; "));

        System.out.println();
        // 在 Java 8 中使用双冒号操作符(double colon operator)
        players.forEach(System.out::println);
    



class AcceptMethod 
    public static void printValur(String str) 
        System.out.println("print value : " + str);
    


class MyTest 
    public static void main(String[] args) 
        List<String> al = Arrays.asList("a", "b", "c", "d");
        al.forEach(AcceptMethod::printValur);
        //下面的方法和上面等价的
        Consumer<String> methodParam = AcceptMethod::printValur; //方法参数
        al.forEach(x -> methodParam.accept(x));//方法执行accept
    


class Employee 
    private String firstName, lastName, job, gender;
    private int salary, age;

    public Employee(String firstName, String lastName, String job,
                    String gender, int age, int salary) 
        this.firstName = firstName;
        this.lastName = lastName;
        this.gender = gender;
        this.age = age;
        this.job = job;
        this.salary = salary;
    

    public String getFirstName() 
        return firstName;
    

    public String getLastName() 
        return lastName;
    

    public String getJob() 
        return job;
    

    public String getGender() 
        return gender;
    

    public void setSalary(int salary) 
        this.salary = salary;
    

    public int getSalary() 
        return salary;
    

    public int getAge() 
        return age;
    

    public static void main(String[] args) 
        List<Employee> javaProgrammers = new ArrayList<Employee>() 
            
                add(new Employee("Elsdon", "Jaycob", "Java programmer", "male", 43, 2000));
                add(new Employee("Tamsen", "Brittany", "Java programmer", "female", 23, 1500));
                add(new Employee("Floyd", "Donny", "Java programmer", "male", 33, 1800));
                add(new Employee("Sindy", "Jonie", "Java programmer", "female", 32, 1600));
                add(new Employee("Vere", "Hervey", "Java programmer", "male", 22, 1200));
                add(new Employee("Maude", "Jaimie", "Java programmer", "female", 27, 1900));
                add(new Employee("Shawn", "Randall", "Java programmer", "male", 30, 2300));
                add(new Employee("Jayden", "Corrina", "Java programmer", "female", 35, 1700));
                add(new Employee("Palmer", "Dene", "Java programmer", "male", 33, 2000));
                add(new Employee("Addison", "Pam", "Java programmer", "female", 34, 1300));
            
        ;

        System.out.println("所有程序员的姓名:");
        javaProgrammers.forEach((p) -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName()));
        System.out.println();
        System.out.println("给程序员加薪 5% :");
        javaProgrammers.forEach(p -> System.out.printf(String.valueOf(p.getSalary()) + "; "));
        Consumer<Employee> giveRaise = e -> e.setSalary(e.getSalary() / 100 * 5 + e.getSalary());
        javaProgrammers.forEach(giveRaise);
        System.out.println();
        javaProgrammers.forEach(p -> System.out.printf(String.valueOf(p.getSalary()) + "; "));
        System.out.println();
        System.out.println("下面是月薪超过 $1,400 的JAVA程序员:");
        javaProgrammers.stream()
                .filter((p) -> (p.getSalary() > 1400))
                .forEach((p) -> System.out.printf("%s %s %s; ", p.getFirstName(), p.getLastName(), p.getSalary()));
        System.out.println();
        // 定义 filters
        Predicate<Employee> ageFilter = (p) -> (p.getAge() > 25);
        Predicate<Employee> salaryFilter = (p) -> (p.getSalary() > 1400);
        Predicate<Employee> genderFilter = (p) -> ("female".equals(p.getGender()));

        System.out.println("年龄大于 24岁的女性 Java programmers:");
        javaProgrammers.stream()
                .filter(ageFilter)
                .filter(salaryFilter)
                .filter(genderFilter)
                .forEach((p) -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName()));
        System.out.println();
        System.out.println("根据 salary 排序 Java programmers:");
        List<Employee> sortedJavaProgrammers = javaProgrammers
                .stream()
                .sorted((p, p2) -> (p.getSalary() - p2.getSalary()))
                .limit(3)
                .collect(Collectors.toList());

        sortedJavaProgrammers.forEach((p) -> System.out.printf("%s %s;%s %n", p.getFirstName(), p.getLastName(), p.getSalary()));

        System.out.println("将 Java programmers 的 first name 拼接成字符串:");
        String javaDevelopers = javaProgrammers
                .stream()
                .map(Employee::getFirstName)
                .collect(Collectors.joining(" ; ")); // 在进一步的操作中可以作为标记(token)
        System.out.println(javaDevelopers);

        System.out.println("将 Java programmers 的 first name 存放到 Set:");
        Set<String> javaDevFirstName = javaProgrammers
                .stream()
                .map(Employee::getFirstName)
                .collect(Collectors.toSet());
        System.out.println(javaDevFirstName);

        System.out.println("将 Java programmers 的 first name 存放到 TreeSet:");
        TreeSet<String> javaDevLastName = javaProgrammers
                .stream()
                .map(Employee::getLastName)
                .collect(Collectors.toCollection(TreeSet::new));
        System.out.println(javaDevLastName);
        System.out.println("计算付给 Java programmers 的所有money:");
        int totalSalary = javaProgrammers
                .parallelStream()
                .mapToInt(p -> p.getSalary())
                .sum();
        System.out.println(totalSalary);
        //计算 count, min, max, sum, and average for numbers
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        IntSummaryStatistics stats = numbers
                .stream()
                .mapToInt((x) -> x)
                .summaryStatistics();

        System.out.println("List中最大的数字 : " + stats.getMax());
        System.out.println("List中最小的数字 : " + stats.getMin());
        System.out.println("所有数字的总和   : " + stats.getSum());
        System.out.println("所有数字的平均值 : " + stats.getAverage());
    

 

结果

所有程序员的姓名:
Elsdon Jaycob; Tamsen Brittany; Floyd Donny; Sindy Jonie; Vere Hervey; Maude Jaimie; Shawn Randall; Jayden Corrina; Palmer Dene; Addison Pam; 
给程序员加薪 5% :
2000; 1500; 1800; 1600; 1200; 1900; 2300; 1700; 2000; 1300; 
2100; 1575; 1890; 1680; 1260; 1995; 2415; 1785; 2100; 1365; 
下面是月薪超过 $1,400 的JAVA程序员:
Elsdon Jaycob 2100; Tamsen Brittany 1575; Floyd Donny 1890; Sindy Jonie 1680; Maude Jaimie 1995; Shawn Randall 2415; Jayden Corrina 1785; Palmer Dene 2100; 
年龄大于 24岁的女性 Java programmers:
Sindy Jonie; Maude Jaimie; Jayden Corrina; 
根据 salary 排序 Java programmers:
Vere Hervey;1260 
Addison Pam;1365 
Tamsen Brittany;1575 
将 Java programmers 的 first name 拼接成字符串:
Elsdon ; Tamsen ; Floyd ; Sindy ; Vere ; Maude ; Shawn ; Jayden ; Palmer ; Addison
将 Java programmers 的 first name 存放到 Set:
[Elsdon, Shawn, Palmer, Addison, Maude, Floyd, Vere, Tamsen, Jayden, Sindy]
将 Java programmers 的 first name 存放到 TreeSet:
[Brittany, Corrina, Dene, Donny, Hervey, Jaimie, Jaycob, Jonie, Pam, Randall]
计算付给 Java programmers 的所有money:
18165
List中最大的数字 : 10
List中最小的数字 : 1
所有数字的总和   : 55
所有数字的平均值 : 5.5

.

以上是关于java Lambda的主要内容,如果未能解决你的问题,请参考以下文章

Android开发太难了:Java Lambda ≠ Android Lambda (上)

Android开发太难了:Java Lambda ≠ Android Lambda (上)

JAVA由一个将JSONArray转成Map的需求引发的lambda语法的学习

Java -- 每日一问:有人说“Lambda能让Java程序慢30倍”,你怎么看?

Java 8 新特性总结

函数式编程