lambda
参考:https://www.cnblogs.com/franson-2016/p/5593080.html
Lambda表达式的语法
基本语法:
(parameters) -> expression
或
(parameters) ->{ statements; }
lambda支持jdk1.8及以上。
我刚开始使用Myeclipse
Version: 2014
Build id: 12.0.0-20131202
不支持jdk1.8,要安装java8的插件,结果插件安装不了,所以我使用idea。
应用:
1.for循环
1 public void test01(){ 2 String[] atp = {"Rafael Nadal", "Novak Djokovic", 3 "Stanislas Wawrinka", 4 "David Ferrer","Roger Federer", 5 "Andy Murray","Tomas Berdych", 6 "Juan Martin Del Potro"}; 7 List<String> players = Arrays.asList(atp); 8 // 以前for循环 9 for (String player : players) { 10 System.out.println(player); 11 } 12 // 使用 lambda 表达式以及函数操作(functional operation) 13 players.forEach((player) -> System.out.print(player + "; ")); 14 // 在 Java 8 中使用双冒号操作符(double colon operator) 15 players.forEach(System.out::println); 16 }
2.匿名内部类(以Runnable为例)
1 public void test02(){ 2 //使用匿名内部类 3 new Thread(new Runnable() { 4 @Override 5 public void run() { 6 System.out.println("hello world!"); 7 } 8 }).start(); 9 //使用lambda 10 new Thread(() -> System.out.println("hello world!")).start(); 11 //使用匿名内部类 12 Runnable r1=new Runnable() { 13 @Override 14 public void run() { 15 System.out.println("hello world!"); 16 } 17 }; 18 r1.run(); 19 //使用lambda 20 Runnable r2 = () -> System.out.println("hello wrold!"); 21 r2.run(); 22 }
3.使用Lambdas排序集合
1 public void test03(){ 2 String[] players = {"Rafael Nadal", "Novak Djokovic", 3 "Stanislas Wawrinka", "David Ferrer", 4 "Roger Federer", "Andy Murray", 5 "Tomas Berdych", "Juan Martin Del Potro", 6 "Richard Gasquet", "John Isner"}; 7 8 // 1.1 使用匿名内部类根据 name 排序 players 9 Arrays.sort(players, new Comparator<String>() { 10 @Override 11 public int compare(String s1, String s2) { 12 return (s1.compareTo(s2)); 13 } 14 }); 15 //使用lambda创建比较器 16 Comparator<String> com = (String s1, String s2) -> (s1.compareTo(s2)); 17 Arrays.sort(players,com); 18 Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2))); 19 //其他排序 20 // 使用匿名内部类根据 surname 排序 players 21 Arrays.sort(players, new Comparator<String>() { 22 @Override 23 public int compare(String s1, String s2) { 24 return (s1.substring(s1.indexOf(" ")).compareTo(s2.substring(s2.indexOf(" ")))); 25 } 26 }); 27 // 使用 lambda expression 排序,根据 surname 28 Comparator<String> sortBySurname = (String s1, String s2) -> 29 ( s1.substring(s1.indexOf(" ")).compareTo( s2.substring(s2.indexOf(" ")) ) ); 30 Arrays.sort(players, sortBySurname); 31 // 或者这样 32 Arrays.sort(players, (String s1, String s2) -> 33 ( s1.substring(s1.indexOf(" ")).compareTo( s2.substring(s2.indexOf(" ")) ) ) 34 ); 35 // 使用匿名内部类根据 name lenght 排序 players 36 Arrays.sort(players, new Comparator<String>() { 37 @Override 38 public int compare(String s1, String s2) { 39 return (s1.length() - s2.length()); 40 } 41 }); 42 // 使用 lambda expression 排序,根据 name lenght 43 Comparator<String> sortByNameLenght = (String s1, String s2) -> (s1.length() - s2.length()); 44 Arrays.sort(players, sortByNameLenght); 45 // or this 46 Arrays.sort(players, (String s1, String s2) -> (s1.length() - s2.length())); 47 // 使用匿名内部类排序 players, 根据最后一个字母 48 Arrays.sort(players, new Comparator<String>() { 49 @Override 50 public int compare(String s1, String s2) { 51 return (s1.charAt(s1.length() - 1) - s2.charAt(s2.length() - 1)); 52 } 53 }); 54 // 使用 lambda expression 排序,根据最后一个字母 55 Comparator<String> sortByLastLetter = 56 (String s1, String s2) -> 57 (s1.charAt(s1.length() - 1) - s2.charAt(s2.length() - 1)); 58 Arrays.sort(players, sortByLastLetter); 59 // or this 60 Arrays.sort(players, (String s1, String s2) -> (s1.charAt(s1.length() - 1) - s2.charAt(s2.length() - 1))); 61 }
4.使用Lambdas和Streams
1>创建Person类
1 public class Person { 2 3 private String firstName, lastName, job, gender; 4 private int salary, age; 5 6 public Person(String firstName, String lastName, String job, 7 String gender, int age, int salary) { 8 this.firstName = firstName; 9 this.lastName = lastName; 10 this.gender = gender; 11 this.age = age; 12 this.job = job; 13 this.salary = salary; 14 } 15 // Getter and Setter 16 // . . . . . 17 }
2>创建两个list
1 List<Person> javaProgrammers = new ArrayList<Person>() { 2 { 3 add(new Person("Elsdon", "Jaycob", "Java programmer", "male", 43, 2000)); 4 add(new Person("Tamsen", "Brittany", "Java programmer", "female", 23, 1500)); 5 add(new Person("Floyd", "Donny", "Java programmer", "male", 33, 1800)); 6 add(new Person("Sindy", "Jonie", "Java programmer", "female", 32, 1600)); 7 add(new Person("Vere", "Hervey", "Java programmer", "male", 22, 1200)); 8 add(new Person("Maude", "Jaimie", "Java programmer", "female", 27, 1900)); 9 add(new Person("Shawn", "Randall", "Java programmer", "male", 30, 2300)); 10 add(new Person("Jayden", "Corrina", "Java programmer", "female", 35, 1700)); 11 add(new Person("Palmer", "Dene", "Java programmer", "male", 33, 2000)); 12 add(new Person("Addison", "Pam", "Java programmer", "female", 34, 1300)); 13 } 14 }; 15 16 List<Person> phpProgrammers = new ArrayList<Person>() { 17 { 18 add(new Person("Jarrod", "Pace", "PHP programmer", "male", 34, 1550)); 19 add(new Person("Clarette", "Cicely", "PHP programmer", "female", 23, 1200)); 20 add(new Person("Victor", "Channing", "PHP programmer", "male", 32, 1600)); 21 add(new Person("Tori", "Sheryl", "PHP programmer", "female", 21, 1000)); 22 add(new Person("Osborne", "Shad", "PHP programmer", "male", 32, 1100)); 23 add(new Person("Rosalind", "Layla", "PHP programmer", "female", 25, 1300)); 24 add(new Person("Fraser", "Hewie", "PHP programmer", "male", 36, 1100)); 25 add(new Person("Quinn", "Tamara", "PHP programmer", "female", 21, 1000)); 26 add(new Person("Alvin", "Lance", "PHP programmer", "male", 38, 1600)); 27 add(new Person("Evonne", "Shari", "PHP programmer", "female", 40, 1800)); 28 } 29 };
3>输出
1 System.out.println("所有程序员的姓名:"); 2 javaProgrammers.forEach((p) -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName())); 3 phpProgrammers.forEach((p) -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName()));
4>使用forEach方法,增加程序员的工资5%
1 System.out.println("给程序员加薪 5% :"); 2 Consumer<Person> giveRaise = e -> e.setSalary(e.getSalary() / 100 * 5 + e.getSalary()); 3 4 javaProgrammers.forEach(giveRaise); 5 phpProgrammers.forEach(giveRaise);
5>使用filter
1 System.out.println("下面是月薪超过 $1,400 的PHP程序员:") 2 phpProgrammers.stream() 3 .filter((p) -> (p.getSalary() > 1400)) 4 .forEach((p) -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName())); 5 // 定义 filters 6 Predicate<Person> ageFilter = (p) -> (p.getAge() > 25); 7 Predicate<Person> salaryFilter = (p) -> (p.getSalary() > 1400); 8 Predicate<Person> genderFilter = (p) -> ("female".equals(p.getGender())); 9 10 System.out.println("下面是年龄大于 24岁且月薪在$1,400以上的女PHP程序员:"); 11 phpProgrammers.stream() 12 .filter(ageFilter) 13 .filter(salaryFilter) 14 .filter(genderFilter) 15 .forEach((p) -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName())); 16 17 // 重用filters 18 System.out.println("年龄大于 24岁的女性 Java programmers:"); 19 javaProgrammers.stream() 20 .filter(ageFilter) 21 .filter(genderFilter) 22 .forEach((p) -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName()));
6>使用stream排序
1 System.out.println("根据 name 排序,并显示前5个 Java programmers:"); 2 List<Person> sortedJavaProgrammers = javaProgrammers 3 .stream() 4 .sorted((p, p2) -> (p.getFirstName().compareTo(p2.getFirstName()))) 5 .limit(5) 6 .collect(toList()); 7 8 sortedJavaProgrammers.forEach((p) -> System.out.printf("%s %s; %n", p.getFirstName(), p.getLastName())); 9 10 System.out.println("根据 salary 排序 Java programmers:"); 11 sortedJavaProgrammers = javaProgrammers 12 .stream() 13 .sorted( (p, p2) -> (p.getSalary() - p2.getSalary()) ) 14 .collect( toList() ); 15 16 sortedJavaProgrammers.forEach((p) -> System.out.printf("%s %s; %n", p.getFirstName(), p.getLastName()));
7>结合 map 方法,我们可以使用 collect 方法来将我们的结果集放到一个字符串,一个 Set 或一个TreeSet中
1 System.out.println("将 PHP programmers 的 first name 拼接成字符串:"); 2 String phpDevelopers = phpProgrammers 3 .stream() 4 .map(Person::getFirstName) 5 .collect(joining(" ; ")); // 在进一步的操作中可以作为标记(token) 6 7 System.out.println("将 Java programmers 的 first name 存放到 Set:"); 8 Set<String> javaDevFirstName = javaProgrammers 9 .stream() 10 .map(Person::getFirstName) 11 .collect(toSet()); 12 13 System.out.println("将 Java programmers 的 first name 存放到 TreeSet:"); 14 TreeSet<String> javaDevLastName = javaProgrammers 15 .stream() 16 .map(Person::getLastName) 17 .collect(toCollection(TreeSet::new));
8>Streams 还可以是并行的(parallel)
1 System.out.println("计算付给 Java programmers 的所有money:"); 2 int totalSalary = javaProgrammers 3 .parallelStream() 4 .mapToInt(p -> p.getSalary()) 5 .sum();