람다식

염지은·2021년 12월 12일
0

java

목록 보기
44/45

[ 람다식 ]

  • jdk1.8 버전에서 추가된 기능

  • 메소드를 하나의 식으로 간단하게 표현한것

  • 형식
    (자료형 변수)-> {메소드 실행코드;}

  • 함수형 인터페이스에서만 람다식을 사용할 수 있다.
    함수형 인터페이스 : 추상메소드를 하나만 갖고 있는 인터페이스.(예:Runnable)

    interface MyMath{
    	int add(int a,int b);
    }
    interface Shape{
    	void draw();
    }
    interface MyCircle{
    	double getArea(double r);
    }
    public class Test06_Lambda {
    	public static void main(String[] args) {
    		MyMath m=new MyMath() {
    			public int add(int a,int b) {
    				return a+b;
    			}
    		};
    		int n=m.add(1,2);
    		System.out.println(n);
    
    		MyMath m1=(a,b)->{return a+b;};
    		System.out.println("두수합:" + m1.add(1,2));
    	
    		Shape s=()->{ 
    			System.out.println("사각형그리기");
    			System.out.println("사각형칠하기");
    		};
    		s.draw();
    		
    	
    		MyCircle mc=r->r*r*3.14;//리턴문장이 딱 하나만 있는경우는 {}와 return을 안써도 됨
    		System.out.println("원의넓이:" + mc.getArea(10));
           		new Thread(()->{
    			while(true) {
    				Date d=new Date();
    				//출력할 날짜형식 설정
    				SimpleDateFormat sf=new SimpleDateFormat("yyyy년MM월dd일 HH:mm:ss");
    				//date객체를 지정할 날짜형식으로 문자열을 만들어 리턴
    				String s1=sf.format(d);
    				System.out.println(s1);
    				try {
    					Thread.sleep(1000);
    				}catch(InterruptedException ie) {
    					System.out.println(ie.getMessage());
    				}
    			}
    		}).start();
    	}
    }
    		

0개의 댓글