1. 通过Lambda 调用接口
public interface MyInterface {
String getBuildString(String name);
}
public class Application {
public static void main(String args[]) {
System.out.println("test .....");
/**
* 1.无需定义参数类型;
* 2.一个参数可以不适用圆括号,多个参数必须用圆括号;
*/
MyInterface newName = (name) -> "prefix" + name;
MyInterface newName2 = (p) -> "prefix" + p;
System.out.println("test ....." + newName.getBuildString("Tom"));
System.out.println("test ....." + newName2.getBuildString("Kate"));
}
}
public class MyTest {
public static void main(String args[]) {
//常规的写法
Thread th = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程测试");
}
});
th.start();
//使用lambda 后的写法
/**
* 主体只有一个语句,可以省略大括号,主体有多个语句必须使用大括号;
*/
// 写法1
new Thread(()->System.out.println("主体只有一个语句可以省略大括号测试")).start();
//写法 2
Thread th2 = new Thread(()->{System.out.println("多条语句执行测试1");System.out.println("多条语句执行测试2");});
th2.start();
}
}
2. 通过Lambda 迭代循环
import java.util.HashMap;
import java.util.Map;
public class MyTest {
public static void main(String args[]) {
Map<String, String> items = new HashMap<String, String>();
items.put("key1","Value1");
items.put("key2","Value1");
items.put("key3","Value1");
//常规方法迭代取值
for(Map.Entry<String, String> entry : items.entrySet()){
System.out.println("常规方法迭代取值:"+entry.getKey()+":"+entry.getValue());
}
//通过Lambda取值
items.forEach((k,v)->{
System.out.println("通过Lambda取值:"+k+":"+v);
});
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyTest {
public static void main(String args[]) {
List<String> items = new ArrayList<String>();
items.add("list1");
items.add("list2");
items.add("list3");
items.forEach(item-> System.out.println("list Value :"+item+""));
items.forEach(System.out::println);
//取出包含字符2的项
items.stream().filter(s -> s.contains("2")).forEach(i-> System.out.println("过滤后的值:"+i));
items.stream().filter(s -> s.contains("2")).forEach(System.out::println);
}
}