1、新增接口的默认方法,使用default关键字
接口可以有实现方法,并且不需要实现类去实现其方法。
package com.test.java8;
public interface Formula {
double calculate(int num);
//Java8新增,接口的默认方法
default double sqrt(int num){
return Math.sqrt(num);
}
}
package com.test.java8;
public class FormulaTest {
public static void main(String[] args){
Formula formula = new Formula() {
//仅仅实现接口Formula定义中未实现的接口
@Override
public double calculate(int num) {
//使用default关键字的方法直接使用
return sqrt(num * 100);
}
};
System.out.println("The result of calculate is :" + formula.calculate(100));
System.out.println("The result of sqrt is :" + formula.sqrt(25));
}
}
2、Lambda表达式
给我的第一感觉是使用了Lambda表达式之后,代码变得更加简洁;另一方面,编码习惯完全被改变。线面看几行简单的代码。
package com.test.java8;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class LambdaTest {
public static void main(String[] args){
//老版本Java
List<String> nameList = Arrays.asList("test1","test3","test2");
Collections.sort(nameList, new Comparator<String>() {
@Override
public int compare(String obj1, String obj2) {
return obj2.compareTo(obj1);
}
});
//新版本Java8更加简洁
Collections.sort(nameList, (String name1,String name2) -> {
return name2.compareTo(name1);
});
Collections.sort(nameList, (String name1,String name2) -> name2.compareTo(name1));
Collections.sort(nameList,(name1,name2) -> name2.compareTo(name1));
nameList.forEach((name) -> System.out.println("username:" + name));
}
}
3、方法引用
package com.ali.test; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * Created by hjwue on 2016/11/24. */ public class MethodReferenceTest { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setLayout(new FlowLayout()); frame.setVisible(true); JButton btn1 = new JButton("点我"); JButton btn2 = new JButton("也点我"); frame.getContentPane().add(btn1); frame.getContentPane().add(btn2); //使用Lambda表达式方式 btn1.addActionListener(e -> { System.out.println("这里是Lambda实现方式"); }); //使用方法引用方法 btn2.addActionListener(MethodReferenceTest::doSomething); } public static void doSomething(ActionEvent e){ System.out.println("这里是方法引用实现方式"); } }