1.lambda表达式
替换匿名类:
比如大多匿名内部类的多行代码中仅有一行在做实际工作。
public class lambada { //正常线程启动 public static void runSomeThing(){ Runnable runnable = new Runnable() { public void run() { System.out.println("I am running"); } }; new Thread(runnable).start(); } //使用lambda式之后的 public static void runSomeThingByLambda(){ new Thread(() -> System.out.println("I am running")).start(); } public static void test2(){ Runnable r = () -> System.out.println("do something."); } public static void main(String[] args) { // runSomeThing(); runSomeThingByLambda(); // test2(); } }
List表进行迭代
// Java 8之前: public static void List(){ List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); for (Object feature : features) { System.out.println(feature); } } public static void ListNew(){ List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); features.forEach(n->System.out.println(n)); } // 使用Java 8的方法引用更方便,方法引用由::双冒号操作符标示, // 看起来像C++的作用域解析运算符 public static void ListNew2(){ List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); features.forEach(System.out::println); }
2.什么是函数式编程
在思考问题时,使用不可变值和函数,函数对一个值进行处理,映射成另一个值。
例子
import java.util.function.Consumer; public class CookingDemo { //Consumer<T>用于接收一个对象进行处理但没有返回,比如接收一个人并打印他的名字 public void doTask(String materia, Consumer<String> consumer) { consumer.accept(materia); } public static void main(String[] args) { CookingDemo cookingDemo = new CookingDemo(); // cookingDemo.doTask("蔬菜", material -> System.out.println("清洗" + material)); cookingDemo.doTask("蔬菜",material -> System.out.println("清洗" + material)); cookingDemo.doTask("蔬菜", material -> System.out.println(material + "切片")); cookingDemo.doTask("食用油", material -> System.out.println(material + "烧热")); cookingDemo.doTask("", material -> System.out.println("炒菜")); } }
输出结果:
清洗蔬菜
蔬菜切片
食用油烧热
炒菜
文章来源: java8的新特性