遍历集合

  1. package cn.unuuc.java;
  2. import java.util.ArrayList;
  3. import java.util.function.Consumer;
  4. public class TestLambda {
  5. public static void main(String[] args) {
  6. ArrayList<String> list = new ArrayList<>();
  7. list.add("hello");
  8. list.add("world");
  9. list.add("!");
  10. list.forEach(new Consumer<String>() {
  11. @Override
  12. public void accept(String s) {
  13. System.out.println(s);
  14. }
  15. });
  16. list.forEach(s -> System.out.println(s));
  17. }
  18. }

forEach 方法内,其形参为一个 Consumer 函数接口,所以可以通过Lambda来简化代码

集合排序

  1. @Test
  2. public void test08(){
  3. ArrayList<UserEntity> userEntities = new ArrayList<>();
  4. userEntities.add(new UserEntity("小明",12));
  5. userEntities.add(new UserEntity("小红",22));
  6. userEntities.add(new UserEntity("小蓝",13));
  7. userEntities.add(new UserEntity("小绿",16));
  8. userEntities.add(new UserEntity("小紫",21));
  9. userEntities.sort(new Comparator<UserEntity>() {
  10. @Override
  11. public int compare(UserEntity o1, UserEntity o2) {
  12. return o1.getAge()- o2.getAge();
  13. }
  14. });
  15. userEntities.forEach((u)-> System.out.println(u.toString()));
  16. // Lambda 实现排序
  17. userEntities.sort(((o1, o2) -> o1.getAge()-o2.getAge()));
  18. userEntities.forEach((u)-> System.out.println(u.toString()));
  19. }

实现线程调用

  1. package cn.unuuc.java;
  2. public class Test {
  3. public static void main(String[] args) {
  4. new Thread(new Runnable() {
  5. @Override
  6. public void run() {
  7. System.out.println(Thread.currentThread().getName());
  8. }
  9. }).start();
  10. // Lambda
  11. new Thread(()-> System.out.println(Thread.currentThread().getName())).start();
  12. }
  13. }

应为Runnable 为一个函数接口
image.png