Java

java 람다식 lamda 여러가지 응용하기

dev.mk 2020. 4. 25. 21:43
반응형

1. 각종 컬렉션 활용하기.

package study.lamda;
 
 
public class ex20200425_1 {
    
    public static void main(String[] args) {
        
        // 일반 문법 vs 람다 문법 비교!!!
        
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
 
        map1.put("name","일길동");
        map1.put("age""19");
 
        map2.put("name""이길동");
        map2.put("age""29");
 
        List<Map<String,Object>> list = new ArrayList<>();
        list.add(map1);
        list.add(map2);
 
        System.out.println(" ");
        System.out.println("////////////////////////// [1] ///////////////////////////////");
        
        // 기본 list for 
        for (Map<String, Object> map : list) {
            System.out.println("default : "+map);
            System.out.println("default map key: "+map.get("name"));
            
        }
        
        // 출력 결과 
        // default : {name=홍길동, age=29}
        // default map key: 홍길동
        // default : {name=임꺽정, age
        
 
        System.out.println(" ");
        System.out.println("////////////////////////// [2] ///////////////////////////////");
        
        // lambda사용한 List foreach 문
        list.forEach(x -> {
            System.out.println("lamda : "+x);
            System.out.println("lamda map key: "+x.get("name"));
        });
 
        // 출력 결과 
        // lamda : {name=홍길동, age=29}
        // lamda map key: 홍길동
        // lamda : {name=임꺽정, age=30}
        // lamda map key: 임꺽정
        
        
        Map<Integer, Object> tempMap = new HashMap<>();
        Map<String, Object> map3 = new HashMap<>();
        Map<String, Object> map4 = new HashMap<>();
 
        map3.put("name""삼길동");
        map3.put("age""39");
 
        map4.put("name""사길동");
        map4.put("age""49");
 
        // tempMap 안에 List와 Map을 담는다.
        tempMap.put(0, list);
        tempMap.put(1, map3);
        tempMap.put(2, map4);
        
        System.out.println(" ");
        System.out.println("////////////////////////// [3] ///////////////////////////////");
        
        System.out.println("tempMap: "+tempMap);
        // 출력 결과 
        // tempMap: {
        //    0=[
        //        {name=일길동, age=19}, {name=이길동, age=29}
        //    ], 
        //        1={name=삼길동, age=39}, 
        //        2={name=사길동, age=49}
        //    }
        
        
        System.out.println(" ");
        System.out.println("////////////////////////// [4] ///////////////////////////////");
        
        // lambda 사용한 Map foreach
        // for문
        for(int i=0; i< tempMap.size(); i++) {
            System.out.println("tempMap.get(0) : "+tempMap.get(0));
        }
        
        // 출력 결과 
        // tempMap.get(0) : [{name=일길동, age=19}, {name=이길동, age=29}]
        // tempMap.get(0) : [{name=일길동, age=19}, {name=이길동, age=29}]
        // tempMap.get(0) : [{name=일길동, age=19}, {name=이길동, age=29}]
                        
        // foreach문 - keySet사용
        
        System.out.println(" ");
        System.out.println("////////////////////////// [5] ///////////////////////////////");
        
        for ( Integer key : tempMap.keySet() ) {
            System.out.println(" key : "+key );
            System.out.println("tempMap.get(key : "+tempMap.get(key));
        }
        
        // 출력 결과 
        // key : 0
        // tempMap.get(key : [{name=일길동, age=19}, {name=이길동, age=29}]
         // key : 1
        // tempMap.get(key : {name=삼길동, age=39}
         // key : 2
        // tempMap.get(key : {name=사길동, age=49} 
        
        // foreach문 - entrySet사용
        System.out.println(" ");
        System.out.println("////////////////////////// [6] ///////////////////////////////");
        
        for ( Map.Entry<Integer, Object> entry : tempMap.entrySet()) {
            System.out.println("entry.getKey() : "+entry.getKey());
            System.out.println("entry.getValue() : "+entry.getValue());
        }
        
        // 출력 결과
        // entry.getKey() : 0
        // entry.getValue() : [{name=일길동, age=19}, {name=이길동, age=29}]
        // entry.getKey() : 1
        // entry.getValue() : {name=삼길동, age=39}
        // entry.getKey() : 2
        // entry.getValue() : {name=사길동, age=49}
 
        // lambda 사용한 foreach문
        System.out.println(" ");
        System.out.println("////////////////////////// [7] ///////////////////////////////");
        
        tempMap.forEach((k,v) ->{
            System.out.println("key : "+k);
            System.out.println("v : "+v);
        });
 
        // 출력 결과
        // key : 0
        // v : [{name=일길동, age=19}, {name=이길동, age=29}]
        // key : 1
        // v : {name=삼길동, age=39}
        // key : 2
        // v : {name=사길동, age=49}
 
        // lambda 사용한 foreach문
        System.out.println(" ");
        System.out.println("////////////////////////// [8] ///////////////////////////////");
        
        tempMap.forEach((k,v) -> System.out.println("key : "++" v : "+ v));
        
        //출력결과
        // key : 0 v : [{name=일길동, age=19}, {name=이길동, age=29}]
           // key : 1 v : {name=삼길동, age=39}
           // key : 2 v : {name=사길동, age=49}
        
        
 
    }
 
}

2. lambda 로 interface와 추상메소드 호출 / lambda 사용하여 List Stream Method

package study.lamda;
 
 
public class ex20200425_2 {
    
      public static void main(String[] args) {
          
            // 람다 사용한 인터페이스 메소드 호출 1
            func1((i, j)->{
                return  i * j;
            });
            // output : 20000
     
            // 람다 사용한 인터페이스 메소드 호출 2
            myInterface2 addExp1 = (int a, int b) -> a + b;
            myInterface2 addExp2 = (int a, int b) -> { return a + b; };
            myInterface2 sub = (int a, int b) -> a - b;
     
            int result = addExp1.calc(12+ addExp2.calc(12+ sub.calc(-55); // 6 - 10 = -4
            System.out.println("/////////////////////////////////////////");
            System.out.println("result : "+result);
            // output : -4
            
            
            // lambda 사용하여 쓰레드 호출 
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("/////////////////////////////////////////");
                    System.out.println("As-Is Thread Runnable Define");
                }
            }).start();
     
            new Thread(()->{
                System.out.println("/////////////////////////////////////////");
                System.out.println("To-be Thread Lambda Express");
            }).start();
            
            
            // lambda 사용하여 List Stream Method
            List<Integer> list = new ArrayList<>();
            for(int i=0; i<=4; i++) {
                list.add(i);
            }
     
            // 스트림
            list.stream();                
            
            // stream 요소 반복
            System.out.println("stream 요소 반복");
            System.out.println("/////////////////////////////////////////");
            list.stream().forEach(System.out::println);                             
            // 0 1 2 3 4
            
            // stream 요소를 연산가능하게 함
            System.out.println("stream 요소를 연산가능하게 함");
            System.out.println("/////////////////////////////////////////");
            list.stream().map(i -> i*i).forEach(System.out::println);      
            // 0 1 4 9 16
            
            // stream 요소의 인덱스까지 제한함
            System.out.println("stream 요소의 인덱스까지 제한함");
            System.out.println("/////////////////////////////////////////");
            list.stream().limit(1).forEach(System.out::println);                
            // 0
            
            // stream 요소의 인덱스를 생략
            System.out.println("stream 요소의 인덱스를 생략");
            System.out.println("/////////////////////////////////////////");
            list.stream().skip(1).forEach(System.out::println);                
            // 1 2 3 4
            
            // stream 요소를 조건문과 비교하여 필터
            System.out.println("stream 요소를 조건문과 비교하여 필터");
            System.out.println("/////////////////////////////////////////");
            list.stream().filter(i-> i<=1).forEach(System.out::println);     
            // 0 1
            
            // stream 단일요소 반환 0+1+2+3+4
            System.out.println("stream 단일요소 반환 0+1+2+3+4");
            System.out.println("/////////////////////////////////////////");
            list.stream().reduce((a,b)-> a+b).get();                                
            // 10
 
 
     
        }
     
        // 람다식을 위한 인터페이스에서 추상 메소드는 단 하나여야 한다.
        // 어노테이션을 사용함으로써 추상메소드를 1개만 선언할수 있게 제한함.
        @FunctionalInterface
        public interface myInterface1{
            public int compareMethod(int value1, int value2);
        }
     
        @FunctionalInterface
        public interface myInterface2 {
            public int calc(int a, int b);
        }
     
        public static void func1(myInterface1 myinterface1){
            int value1 = 100;
            int value2 = 200;
     
            int finalValue = myinterface1.compareMethod(value1, value2);
            System.out.println("finalValue : "+ finalValue);
        }
}
 

 

본문의 출처 https://shlee0882.tistory.com/100

반응형