lambda使用与未使用的对比
package com.example.demo.test;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
public class LambdaTest {
public static void main(String args[]){
List<String> str = new ArrayList<>();
str.add("a ");
str.add("z ");
str.add("b ");
str.add("g ");
str.add("y ");
List<String> str2 = new ArrayList<>();
str2.add("a ");
str2.add("z ");
str2.add("b ");
str2.add("g ");
str2.add("y ");
LambdaTest tester = new LambdaTest();
System.out.println("使用 Java 7 测试: ");
tester.sortUseJava7(str);
System.out.println(str);
System.out.println("使用 Java 8 测试: ");
tester.sortUseJava8(str2);
System.out.println(str2);
}
private void sortUseJava7(List<String> name){
Collections.sort(name, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
}
private void sortUseJava8(List<String> name){
Collections.sort(name,(o1,o2)->{return o1.compareTo(o2);});
}
}
结果:
使用 Java 7 测试:
[a , b , g , y , z ]
使用 Java 8 测试:
[a , b , g , y , z ]
public static void main(String[] args) {
int num = 1;
Converter<Integer,Integer > s = param -> System.out.println(String.valueOf(param + num));
s.convert(2);
Comparator<String> comparator = ( first,second) -> Integer.compare(first.length(), second.length());
System.out.println(comparator.compare("sfdsfppdsf","sfdsfdsf"));
}
public interface Converter<T1,T2>{
void convert(int i);
}
结果:
3
1