lamda代码演示
public class Person { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Person(){}; public Person(int id,String name){ this.id = id; this.name = name; } }
import com.ruoyi.web.controller.demo.domain.Person;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Test01 {
public static void main(String[] args) {
List<Person> listd = new ArrayList<>();
listd.add(new Person(2,"张三"));
listd.add(new Person(22,"李四"));
listd.add(new Person(12,"王五"));
listd.add(new Person(23,"赵六"));
listd.add(new Person(24,"寒气"));
//常规写法
/*listd.sort(new Comparator<Person>(){
@Override
public int compare(Person o1, Person o2) {
return o1.getId() - o2.getId();
}
});*/
//lamda写法
listd.sort((l1,l2) -> {
return l1.getId() - l2.getId();
});
for (int i = 0; i < listd.size(); i++) {
System.out.println(listd.get(i).getId());
}
}
}
控制台结果:
演示2
写一个函数式接口
public interface Rfunct { void sayHello(String msg); }
测试主类
public class Test02 { public static void main(String[] args) { Rfunct rf = message -> { System.out.println("Hello "+message); }; rf.sayHello("lamda"); } }
控制台结果