public class MyLambda {
public static void main(String[] args) {
/**
* runnable测试
*/
new Thread(() -> System.out.println("1")).start();
/**
* List测试
*/
String[] str = {"111", "222", "333", "444"};
List<String> list = Arrays.asList(str);
list.forEach((n) -> System.out.println(n));
list.forEach(System.out::println);
list.forEach((String s) -> System.out.print(s));
/**
* 这个等于号后面的表达式想要赋予给前面的就一定要是前面的接口的方法. 例如上面我们在Thread中的引用.直接那么写是因为 Thread中指定了要一个Runnable .所以我们可以传入 实现了Runnable的对象
* 也可以传入一个 Runnable接口的内部类 , 也可以用lambel来表示 ()->{} 因为runnable中就一个run()方法
* 也就是说要使用runnable () 这个是要指定一个类型的 .也可以说是接口 lambda只支持函数式接口
* 比如我们下列方法, 就是指定了类型是Runnable 所以才可以赋予 ()->{} 的代码段
* 也可以认为是把右边的代码块赋予左边
*/
Runnable r = () -> System.out.println("hello world");
/**
* 其他例子 在这里我们把接口代码块赋予 给myCall ,但只是赋予过去 , 然后我们调用这个接口代码块. 他就能跑起来啦!!~
*
*/
MyInterface my = (s) -> {
System.out.println("hello" + s.length());
};
new MyCall(my);
new MyCall((s) -> {
System.out.println(s);
});
/**
* 以下例子 就是我们想把一个 Lambda赋予给 Consumer<Integer> ,然后这这个接口也是只有一个抽象方法 ,那我们直接用Lambda给 Consumer添加引用
* 然后因为我们指定了范性的类型 Integer 我们调用方法中有这个范性
* 那:要么 x->{} 要么 (Integer x) -> {}
*/
Consumer<Integer> c = (Integer x) -> System.out.println("x");
c.accept(1);
/**
* 多参数同理 也是两种写法 (Integer x, String y)-{} / (x,y)->{}
*/
BiConsumer<Integer, String> b = (Integer x, String y) -> System.out.println(x + " : " + y);
b.accept(1, "3");
Predicate<String> p = (String s) -> {
return s == null;
};
System.out.println(p.test("166"));
List<String> collected = new ArrayList<>();
collected.add("alpha");
collected.add("beta");
collected = collected.stream().map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));
System.out.println(collected);
System.out.println("____");
String myStr = "123@456@789";
List<Integer> collect = Arrays.stream(myStr.split("@")).mapToInt(mySplitStr -> Integer.valueOf(mySplitStr)).boxed().collect(Collectors.toList());
System.out.println(collect);
}
}
@FunctionalInterface
public interface MyInterface {
public abstract void run(String s);
}
public class MyCall {
public MyCall(MyCall call){}
public MyCall(MyInterface myInterface){
myInterface.run("6");
}
}