參考文章:ImportNew
要在Android開發中使用lambda表達式,首先需要在 Module 的build.gradle中加入:
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
下面是我在Android Studio上寫的一個demo :
/** * java8 lambda表達式學習 * <p> * http://www.importnew.com/16436.html * <p> * Created by javakam on 2018/4/2. */ public class MyLambda { public static void main(String[] args) { demo3(); } //1 lambda表達式實現Runnable private static void demo1() { new Thread(() -> System.out.println("hello lambda")).start(); } //2 進行事件處理 private static void demo2() { // TextView textView=new TextView(context); // textView.setOnClickListener(view-> { // Toast.makeText(context, "click", Toast.LENGTH_SHORT).show()}); } //3 對列表進行迭代 private static void demo3() { List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); features.forEach(n -> System.out.println("")); // 使用Java 8的方法引用更方便,方法引用由::雙冒號操作符標示, // 看起來像C++的作用域解析運算符 features.forEach(System.out::println); } //4 使用lambda表達式和函數式接口Predicate //Predicate非常適合用於做過濾 private static void demo4() { List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp"); System.out.println("Languages which starts with J :"); filter(languages, (str) -> ((String) str).startsWith("J")); System.out.println("Languages which ends with a "); filter(languages, (str) -> str.toString().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) -> ((String) str).length() > 4); } private static void filter(List names, Predicate condition) { for (Object obj : names) { // 使用Predicate的test()方法判斷該對象是否滿足Predicate指定的條件 if (condition.test(obj)) { System.out.println("" + obj); } } //更帥的操作 names.stream().filter(n -> condition.test(n)).forEach(n -> System.out.println("" + n)); // names.stream().filter(n -> condition.test(n)).forEach(System.out::println); } //5 如何在lambda表達式中加入Predicate private static void demo5() { // 甚至可以用and()、or()和xor()邏輯函數來合並Predicate, // 例如要找到所有以J開始,長度為四個字母的名字,你可以合並兩個Predicate並傳入 List languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp"); Predicate<String> startWithJ = n -> n.toString().startsWith("J"); Predicate<String> length4 = n -> n.toString().length() == 4; //and 輸出:Java //languages.stream().filter(startWithJ.and(length4)).forEach(System.out::println); //or 輸出:Java C++ //Predicate<String> havePlusSignal = n -> n.toString().contains("+"); //languages.stream().filter(startWithJ.or(havePlusSignal)).forEach(System.out::println); //negate反面 輸出: Scala C++ Haskell Lisp languages.stream().filter(startWithJ.negate()).forEach(System.out::println); } //6.1 使用lambda表達式的Map和Reduce示例 - Map對象轉換 private static void demo6_1() { // 不使用lambda表達式為每個訂單加上12%的稅 List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500); for (Integer cost : costBeforeTax) { double price = cost + .12 * cost; System.out.println(price); } // 使用lambda 類似於RxJava中的map操作符,都是起到對象轉換的作用 costBeforeTax.stream().map(cost -> cost + 0.12 * cost).forEach(System.out::println); } //6.2 使用lambda表達式的Map和Reduce示例 - Reduce折疊操作 //reduce() 函數可以將所有值合並成一個。eg:SQL中的 sum()、avg() 或者 count() 的聚集函數,實際上就是 reduce 操作,因為它們接收多個值並返回一個值。 private static void demo6_2() { // 為每個訂單加上12%的稅 // 老方法: List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500); double total = 0; for (Integer cost : costBeforeTax) { double price = cost + .12 * cost; total = total + price; } System.out.println("total = " + total); double bill = costBeforeTax.stream().map(cost -> cost + .12 * cost).reduce((sum, price) -> sum + price).get(); System.out.println("bill = " + bill); } //7 通過過濾創建一個String列表 -- filter private static void demo7() { List<String> strList = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp"); // 創建一個字符串列表,每個字符串長度大於2 List<String> filtered = strList.stream().filter(x -> x.length() > 2).collect(Collectors.toList()); System.out.printf("Original List : %s, filtered list : %s %n", strList, filtered); } //8 對列表的每個元素應用函數 private static void demo8() { // 將字符串換成大寫並用橫線鏈接起來 List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K", "Canada"); String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining("-")); System.out.println(G7Countries); } //9 復制不同的值,創建一個子列表 - distinct() 方法來對集合進行去重 private static void demo9() { // 用所有不同的數字創建一個正方形列表 List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4); List<Integer> distinct = numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList()); System.out.printf("Original List : %s , Square Without duplicates : %s %n", numbers, distinct); } //10 計算集合元素的最大值、最小值、總和以及平均值 //summaryStatistics()可以返回IntSummaryStatistics、LongSummaryStatistics 或者 DoubleSummaryStatistic,描述流中元素的各種摘要數據。 private static void demo10() { //獲取數字的個數、最小值、最大值、總和以及平均值 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()); } }
注意:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
features.forEach(n -> System.out.println(""));
forEach需要Android API 至少為24(即minSdkVersion 24)。