[Java 8] 1. 기존 코드와 Lambda식 비교

seony·2023년 4월 23일

java8

목록 보기
1/16

🌱 Lambda

() -> Single Statement or Expression;

() -> { <Multiple Statements> };

🌱 Funcitonal Interfaces

@FunctionalInterface

  • 추상 메서드가 하나만 있을 경우 붙여도 되고 안붙여도 됨

🌱 Runnable Lamba Example

package com.learnJava.lambdas;

public class RunnableLambdaExample {

    public static void main(String[] args) {
        /**
         * prior Java 8
         */
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Inside Runnable 1");
            }
        };

        new Thread(runnable).start();

        /**
         * Java 8 lambda
         */
        Runnable runnableLambda = () -> {
            System.out.println("Inside Runnable 2");
        };

        Runnable runnableLambda1 = () -> {
            System.out.println("Inside Runnable 3");
            System.out.println("Inside Runnable 3");
        };

        new Thread(runnableLambda).start();

        new Thread(runnableLambda1).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Inside Runnable 3.1");
            }
        }).start();

		// most simplest way
        new Thread(() -> System.out.println("Inside Runnable 4")).start();
    }
}

🌱 Comparator Lambda Example

package com.learnJava.lambdas;

import java.util.Comparator;

public class ComparatorLambdaExample {
    public static void main(String[] args) {

        /**
         * prior java 8
         */

        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2); // 0 -> o1 == 02
                                         // 1 -> o1 > o2
                                         // -1 -> o1 < o2
            }
        };
        System.out.println("Result of the comparator is : " + comparator.compare(3, 2));

        Comparator<Integer> comparatorLambda = (Integer a, Integer b) -> a.compareTo(b);

        System.out.println("Result of the comparator using Lambda is : " + comparatorLambda.compare(3, 2));

        Comparator<Integer> comparatorLambda1 = ( a,  b) -> a.compareTo(b);

        System.out.println("Result of the comparator using Lambda is : " + comparatorLambda.compare(3, 2));

    }
}

0개의 댓글