lambda

    技术2022-07-21  105

    package cn.mrhan.study.demo.mianshi;

    import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;

    /**

    lambda表达式优化以下问题:

    1.解决原有匿名内部类语法冗余问题

    2.解决作用域指向不明确问题

    3.解决多余代码产生的高度问题 */ public class LambdaDemo { public static void testList(){ List list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); for(int i =0;i<list.size();i++){ System.out.println(list.get(i)); } for(Integer i:list){ System.out.println(i); } list.forEach(c -> System.out.println©); }

    public static void testMap(){ Map<String,String> map = new HashMap<>(); map.put(“name”,“zhangsan”); map.put(“age”,“24”); for(Map.Entry<String,String> entry:map.entrySet()){ System.out.println(entry.getKey()+":"+entry.getValue()); } map.forEach((key,value)-> System.out.println(key+":"+value)); }

    public static void testThread(){ Thread t1 = new Thread(){ @Override public void run() { for(int i = 10;i>0;i–){ try { Thread.sleep(1000); System.out.println(“线程1:”+i); } catch (InterruptedException e) { e.printStackTrace(); } } } };

    Thread t2 = new Thread(){ @Override public void run() { for(int i = 10;i>0;i--){ try { Thread.sleep(1000); System.out.println("线程2:"+i); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread t3 = new Thread(()->{ System.out.println("hello"); }); Thread t4 = new Thread(()->{ for(int i = 10;i>0;i--){ try { Thread.sleep(1000); System.out.println("线程4:"+i); } catch (InterruptedException e) { e.printStackTrace(); } } }); t1.start(); t2.start(); t3.start(); t4.start();

    }

    public static void main(String[] args) { testList(); testMap(); testThread(); } }

    Processed: 0.015, SQL: 9