标签:一个 main import new t nbsp i++ 接口 out ane
实例:
package com.interfaces; import java.util.Arrays; import java.util.Comparator; public class LengthComparator implements Comparator<String>{ public static void main(String[] args) { // String[] l = {"hello","tom","kimm"}; // Arrays.sort(l,new LengthComparator()); // for (String e:l) { // System.out.println(e); // } Comparator<String> comp =(String first,String second)-> { return first.length()-second.length(); }; String[] l = {"hello","tom","kimm"}; Arrays.sort(l,comp); for (String e:l) { System.out.println(e); } } public int compare(String s1,String s2) { return s1.length() - s2.length(); } }
无须指定lambda表达式的返回类型,lambda表达式的返回类型总是会由上下文推导得出。
函数式接口:
对于只有一个抽象方法的接口,需要这种接口对象时,就可以提供一个lambda表达式,这种接口称为函数式接口。
package com.lambda; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.Timer; public class LambdaTest { public static void main(String[] args) { // TODO Auto-generated method stub Timer t = new Timer(1000,event-> System.out.println("yeah~")); t.start(); JOptionPane.showMessageDialog(null, "Quit program?"); System.exit(0); } }
package com.lambda; public class LambdaTest { public static void main(String[] args) { // TODO Auto-generated method stub repeat(10,()->System.out.println("Aha~")); } public static void repeat(int n,Runnable action) { for (int i=0;i<n;i++) { action.run(); } } }
标签:一个 main import new t nbsp i++ 接口 out ane
原文地址:https://www.cnblogs.com/zenan/p/10180467.html