6、Lambda表达式
6.1无参数无返回值
@Test
public void test1(){
Runnable run1 = new Runnable() {
@Override
public void run() {
System.out.println("传统方式的Runnable");
}
};
Thread t1 = new Thread(run1);
t1.start();
System.out.println("*****************");
Runnable run2 = ()->System.out.println("lambda实现的Runnable");
Thread t2 = new Thread(run2);
t2.start();
}
6.2 有参数有返回值
@Test
public void test2(){
Comparator<Integer> com1 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};
Comparator<Integer> com2 = (o1, o2) -> o1.compareTo(o2);
System.out.println(com1.compare(1,2));
System.out.println(com2.compare(1,2));
}
6.3有参数无返回值
@Test
public void test3(){
Consumer<String> con1 = new Consumer<String>() {
@Override
public void accept(String o) {
System.out.println(o);
}
};
Consumer<String> con2 = o->System.out.println(o);
con1.accept("con1");
con2.accept("con2");
}
6.4无参数有返回值
@Test
public void test4(){
Supplier<String> sup1 = new Supplier<String>() {
@Override
public String get() {
return "sup1";
}
};
Supplier<String> sup2 = ()-> "sup2";
System.out.println(sup1.get());
System.out.println(sup2.get());
}
6.5、lambda 在集合中的应用
@Test
public void tset5(){
String[] strs = new String[]{"1","2","3","4","5"};
List<String> list = Arrays.asList(strs);
for (String str:list) {
System.out.print(str+";");
}
System.out.println();
list.forEach(str->System.out.print(str+";"));
}