论坛首页 编程语言技术论坛

lambda表达式

浏览 1894 次
锁定老帖子 主题:lambda表达式
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2017-10-14  

 

/**
 * lambda表达式
 * Predicate<Integer>
 * Function<Integer, Integer>
 * Consumer<Integer>
 * @author lenovo
 *
 */
public class Test {

 public static void main(String[] args) {

  List<String> 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();
    filter(languages, (str)->true);
   
    System.out.println();
    filter(languages, (str)->false);
   
    System.out.println();
    filter(languages, (str)->((String) str).length() > 4);
   
    Predicate<String> startsWithJ = (n) -> n.startsWith("J");
    filter(languages, startsWithJ);
   
    System.out.println();
    Predicate<String> fourLetterLong = (n) -> n.length() == 4;
    filter(languages, fourLetterLong);
   
    System.out.println();
    Predicate<String> c = (n) -> n.endsWith("a");
    filter2(languages, c);
   
    int incr = 20;  int myNumber = 10;
    modifyTheValue(myNumber, val-> val + incr);
    Function<Integer, Integer> function = val-> val + incr;
    modifyTheValue(myNumber, function);

   
    List<Integer> lt = Arrays.asList(1,3,8,12);
    Predicate<Integer> c1 = (n) -> n > 3;
    Function<Integer, Integer> m = i -> i*2;
    Consumer<Integer> c2 = n -> System.out.println(n);
    lt.stream().filter(c1)
    .map(m).forEach(c2);
   
 }
 
 public static void filter(List<String> names, Predicate condition) {
     for(String name: names)  {
        if(condition.test(name)) {
           System.out.println(name + " ");
        }
     }
   }
 
 public static void filter2(List names, Predicate condition) {
     names.stream().filter((name) -> (condition.test(name)))
         .forEach((name) -> {System.out.println(name + " ");
     });
  }

 static void modifyTheValue(int valueToBeOperated, Function<Integer, Integer> function){
          int newValue = function.apply(valueToBeOperated);
          System.out.println(newValue);
 }

}

   发表时间:2017-10-18   最后修改:2017-10-18
http://edu.51cto.com/course/10768.html
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics