標籤:
一、Lambda運算式的組成主要有傳入參數列表(參數1,參數2,...),箭頭 ->,及傳回值,可以是某個值,或者結構體。
如下舉一個小小的例子:
在沒有使用Lambda運算式時:
import java.util.stream.Stream;/** * * @author Kangjun */public class Demo { public static void main(String[] args){ Dog dog1 = new Dog("dog1",2); Dog dog2 = new Dog("dog2",1); Dog dog3 = new Dog("dog3",3); Dog[] dogs = {dog1,dog2,dog3}; printDogs(dogs); Arrays.sort(dogs, new Comparator<Dog>(){ @Override public int compare(Dog t, Dog t1) { return t.getWeight()-t1.getWeight(); } }); printDogs(dogs); } public static void printDogs(Dog[] dogs){ for(Dog d : dogs){ System.out.println(d); } System.out.println(); }}
加入了Lambda運算式後可以寫成(下面以3種方法實現):
import java.util.stream.Stream;/** * * @author Kangjun */public class Demo { public static void main(String[] args){ Dog dog1 = new Dog("dog1",2); Dog dog2 = new Dog("dog2",1); Dog dog3 = new Dog("dog3",3); Dog[] dogs = {dog1,dog2,dog3}; printDogs(dogs); // Arrays.sort(dogs,(m,n)->m.getWeight()-n.getWeight()); //Lambda方法一 //Arrays.sort(dogs,(Dog m,Dog n)->Integer.compare(m.getWeight(), n.getWeight()));//Lambda方法二 //printDogs(dogs); //方法三 Stream<Dog> dogStream = Stream.of(dogs); Stream<Dog> sortedDogStream = dogStream.sorted((Dog m, Dog n) -> Integer.compare(m.getWeight(), n.getWeight())); sortedDogStream.forEach(d -> System.out.print(d)); } public static void printDogs(Dog[] dogs){ for(Dog d : dogs){ System.out.println(d); } System.out.println(); }}
看完後是不是很激動。
下面再放幾個例子,參才其實現方式:
import java.util.Arrays;/** * * @author Kangjun */public class StandardSyntaxLambda { private static final String[] arr = {"program", "creek", "is", "a", "java", "site"}; public static void main(String[] args){ Arrays.sort(arr, (String a,String b) -> Integer.compare(a.length(), b.length()) ); System.out.println(Arrays.toString(arr)); }}
import java.util.Arrays;/** * * @author Kangjun */public class ParameterTypeInferredLambda { private static final String[] arr = {"program", "creek", "is", "a", "java", "site"}; public static void main(String[] args){ Arrays.sort(arr,(m,n) -> Integer.compare(m.length(), n.length())); System.out.println(Arrays.toString(arr)); }}
import java.util.Arrays;/** * * @author Kangjun */public class MultipleLinesCodeLambda { private static final String[] arr = {"program", "creek", "is", "a", "java", "site"}; public static void main(String[] args){ Arrays.sort(arr,(String m,String n) -> { return m.length() - n.length(); }); System.out.println(Arrays.toString(arr)); } }
import java.util.stream.Stream;/** * * @author Kangjun */public class SingleParameterInferredTypeLambda { private static final String[] arr = {"program", "creek", "is", "a", "java", "site"}; public static void main(String[] args) { Stream<String> arrStream = Stream.of(arr); Stream<String> sortedStream = arrStream.sorted((a, b) -> a.length() - b.length()); sortedStream.forEach(x -> System.out.println(x)); }}
Java Lambda 運算式的幾各形式