前言:学习一下java8新的Lambda表达式
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)
实例1
List
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
public class Test{ public static void main(String[] args) { List<String> currencyList = Arrays.asList("CNY","USD","AUD","EUR","GBP","HKD","JPY","NZD","HKD","SGD"); System.out.println("Java8 lambda:"); currencyList.forEach(x -> System.out.println(x));
System.out.println("Java8 方法引用"); currencyList.forEach(System.out::println); } }
|
线程
1 2 3 4 5 6 7 8 9
|
public class Test{ public static void main(String[] args) { new Thread( () -> System.out.println("Java8 lambda") ).start(); } }
|
实例2
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
public class Money { private double amount; private String currency; public Money(){}; public Money(double amount,String currency){ this.amount = amount; this.currency = currency; }
public double getAmount() { return amount; }
public void setAmount(double amount) { this.amount = amount; }
public String getCurrency() { return currency; }
public void setCurrency(String currency) { this.currency = currency; } }
|
Test
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import java.util.*;
public class Test { public static void main(String[] args) { Map<String,String> currencyMap = new HashMap<String,String>(); currencyMap.put("CNY","¥"); currencyMap.put("USD","$"); currencyMap.put("AUD","$"); currencyMap.put("EUR","€"); currencyMap.put("GBP","£"); List<Money> moneyList = new ArrayList<Money>(); moneyList.add(new Money(15090, "CNY")); moneyList.add(new Money(33200, "USD")); moneyList.add(new Money(46500, "AUD")); moneyList.add(new Money(76320, "EUR")); moneyList.add(new Money(26760, "GBP"));
List<String> list = new ArrayList<String>(); moneyList.forEach(money -> { list.add(money.getAmount() + currencyMap.get(money.getCurrency())); }); list.forEach(s ->{ System.out.println(s); }); } }
|