//不使用Lambda表达式 new Thread(new Runnable(){ @Override publicvoidrun(){ System.out.println("Before Java8, too much code for too little to do"); } }).start();
1 2 3 4 5
//使用Lambda表达式 new Thread(()->{ System.out.println("Before Java8, too much code for too little to do"); }).start(); //这里的花括号可以省略,有多个语句时就需要写花括号
如果你的方法接收两个参数,那么可以这么写:
1 2
//可以省略int (int even,int odd) -> even + odd
用Lambda表达式进行事件处理
1 2 3 4 5 6 7 8
// 不使用Lambda表达式 JButton show = new JButton("Show"); show.addActionListener(new ActionListener() { @Override publicvoidactionPerformed(ActionEvent e){ System.out.println("Event handling without lambda expression is boring"); } });
1 2 3
show.addActionListener((e)->{ System.out.println("Event handling without lambda expression is boring"); });
用Lambda表达式对列表进行迭代
1 2 3 4 5
// 不使用Lambda表达式 List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); for (String feature : features) { System.out.println(feature); }
1 2 3 4 5 6
//使用Lambda表达式 List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); features.forEach((n)->System.out.println(n));
publicstaticvoidmain(args[]){ List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp"); System.out.println("Languages which starts with J :"); filter(languages, (str)->str.startsWith("J")); System.out.println("Languages which ends with a "); filter(languages, (str)->str.endsWith("a")); System.out.println("Print all languages :"); filter(languages, (str)->true); System.out.println("Print no language : "); filter(languages, (str)->false); System.out.println("Print language whose length greater than 4:"); filter(languages, (str)->str.length() > 4); }
//获取数字的个数、最小值、最大值、总和以及平均值 List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29); IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics(); System.out.println("Highest prime number in List : " + stats.getMax()); System.out.println("Lowest prime number in List : " + stats.getMin()); System.out.println("Sum of all prime numbers : " + stats.getSum()); System.out.println("Average of all prime numbers : " + stats.getAverage());