개발팀
패러다임의 변환
GUI 기반의 객체지향 프로그래밍 (Web)
Text기반의 절차적 프로그래밍 (C/S)
멀티코어 배경의 함수형 프로그램(Big-data)
# JAVA8 특징
= 람다식(Lambda Expression)
- 스트림(Stream) API
- 기본 메서드(Default Method)
= Joda Time 방식의 새 날짜 API 변경 (JSR 310)
= 새 자바스크립트 엔진, 나즈혼(Nashorn)
= 자바 FX 8
= 메타 데이터 지원 보완
= 동시성 API 개선
= IO/NIO 확장
= Heap에서 영속 세대(Permanent Generation) 제거
싱글코어 더블코어
# 어떻게?
= Thread, Lock, memory model
= Thread pool, concurrent collection
= Fork / join framework
 Functional Programming
H/W 에 따른 S/W 개발…
‘람다 그거 별 것 아닌 것?’
- 그 별것 아닌 것 같은 람다를 오랫동안 자바에서 지원하지 못한 이유?
람다식(Lambda Expression)
= 클래스 없이 메서드 정의 수준으로 인자로 전달할 로직을 표현할 수 있는 표기법
= 익명 메서드 (블로저, 블록)
Collections.sort(theListOfMyClasses, new Comparator<MyClass>() {
public int compare(MyClass a, MyClass b) {
return b.getValue() - a.getValue();
}
});
theListOfMyClasses.sort((MyClass a, MyClass b) -> {
return a.getValue() - b.getValue();
});
theListOfMyClasses.sort((a, b) -> a.getValue() - b.getValue());
람다 매개변수 -> 람다 본문
= 매개변수의 타입을 추론
= 자바의 if, for 문 등 블럭을 생략
= return 구문도 제거
= 매개변수가 하나 뿐이라면 괄호도 생략 가능
람다식(Lambda Expression)
자바에서 람다식이 필요한 이유
(1) 외부 이터레이션과 내부 이터레이션
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
for (int number : numbers) {
System.out.println(number);
}
numbers.forEach(new Consumer<Integer>() { //이름뿐인 내부 클래스 생성
public void accept(Integer value) {
System.out.println(value);
}
});
Numbers.forEach((Integer value) -> System.out.println(value)); // 매개변수 -> 몸체
numbers.forEach(value -> System.out.println(value)); //인수 타입 추론
numbers.forEach(System.out::println); // :: method reference
자바에서 람다식이 필요한 이유
(2) 값만 전달하는 대신 작동 방식도 전달하기
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
public int sumAll(List<Integer> numbers) {
int total = 0;
for (int number : numbers) {
total += number; }
return total;
}
public int sumAllEven(List<Integer> numbers) {
int total = 0;
for (int number : numbers) {
if (number % 2 == 0) {
total += number; } }
return total;
}
public int sumAll(List<Integer> numbers, Predicate<Integer> p) { //고차(high order) 함수
int total = 0;
for (int number : numbers) {
if (p.test(number)) {
total += number;
}
}
return total;}
sumAll(numbers, n -> true);
sumAll(numbers, n -> n % 2 == 0);
sumAll(numbers, n -> n > 3);
자바에서 람다식이 필요한 이유
(3) 지연 연산(laziness) 을 통한 효율성
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
for (int number : numbers) {
if (number % 2 == 0) {
int n2 = number * 2;
if (n2 > 5) {
System.out.println(n2);
break;}
}
}
public boolean isEven(int number) {
return number % 2 == 0;
}
List<Integer> l1 = new ArrayList<Integer>();
for (int n : numbers) {
if (isEven(n)) l1.add(n);
}
List<Integer> l2 = new ArrayList<Integer>();
for (int n : l1) {
l2.add(doubleIt(n));
}
System.out.println(l2.get(0));
System.out.println(
numbers.stream()
.filter(Lazy::isEven)
.map(Lazy::doubleIt)
.filter(Lazy::isGreaterThan5)
.findFirst()
);
자바에서 람다식이 필요한 이유
(4) 빌려쓰기(loan) 패턴
public class Resource {
public Resource() {
System.out.println("Opening resource");
}
public void operate() {
System.out.println("Operating on resource");
}
public void dispose() {
System.out.println("Disposing resource");
}
}
Rsource resource = new Resource();
resource.operate();
resource.dispose();
Resource resource = new Resource();
try {
resource.operate();
} finally {
resource.dispose();
}
public static void withResource(Consumer<Resource>
consumer) {
Resource resource = new Resource();
try {
consumer.accept(resource);
} finally {
resource.dispose();
}
}
withResource(resource -> resource.operate());
람다식(Lambda Expression) 왜?
함수형 프로그래밍(Functional Programming)
X1 R1
Input  output
A 10
Input  output
A 10
Input  output
A 10
10분 후~
10년 후~
# Function?
X2 -> R1?
함수형 프로그램(Functional Program) 의 특징
# 불변성 (Immutable)
: 객체의 상태가 불변
int n = 10;
private static final n = 100; //불변
# 참조 투명성(Referential Transparency)
: 함수를 호출하는 부분을 그 함수가 반환하는 결과를 대체했을때, 사이드 이펙트가 없는 것
int plusOne(int x)
{
return x+1;
}
# 1종 객체로서의 함수 (First-Class Function)
= 함수(또는 메서드)를 값으로 취급함수 파라미터로 넘길 수 있고, 리턴값으로도 사용할 수 있으며,
변수에도 할당할 수 있고, 런타임에도 생성될 수 있다는 의미
= 람다표현식과 메서드레퍼런스 기능으로 보다 효율적으로 인자값으로 취급 가능
(cf. 자바7 인터페이스와 익명클래스를 이용하여 인자 값으로 취급)
- int someFunction(another function)
- Function someFunction(int i)
- list= [function, function2, function3]
함수형 프로그램(Functional Program) 의 특징
# 선언적 프로그래밍(Declarative Programming)
= 함수형 프로그래밍은 함수간의 속성과 관계를 선언하여 최종 결과를 계산하는 것을 방법을 기술.
cf. 객체지향 프로그래밍은 프로그램이 절차적인 상태에 따라 '어떤 방법으로 동작' 해야하는지 기술하는
명령형 프로그램.
함수형 프로그램(Functional Program) 의 특징
기본 메서드(Default Method)
= 문제점
: 인터페이스에 메서드를 추가하면 하위 호환성이 깨지기 때문에 해당 인터페이스를 구현한
모든 클래스에 새로 추가된 메서드를 구현하고 이 인터페이스를 사용하는 모든 코드가 새로 컴파일 필요
= 기본 메서드 개념 추가
: 하위 호환성 문제없이 인터페이스에 새로운 메서드를 추가할 수 있게 됨
= 기본 메서드란 인터페이스에 구현된 메서드로서 인터페이스를 구현하는 클래스가
오버라이드 하지 않을 경우 기본 구현물로 적용
//JAVA 8 이전
public interface TestInterface {
public void action(){
System.out.println("Test");
}
}
//Abstract methods do not specify a body!
//인터페이스의 Abstract Method들에 대한 기본기능을 지정
public interface Student {
default void readBook(){
System.out.println("reading book");
}
}
public class GoSam implements Student {
public static void main(String ar[]){
GoSam gosam = new GoSam();
gosam.readBook();
}
}
새 날짜 API
# JDK 기존 날짜, 시간 클래스의 문제점
= 불변 객체가 아니다(not immutable)
: Calendar 객체나 Date 객체가 여러 객체에서 공유되면?
= int 상수 필드의 남용
: calendar.add(Calendar.SECOND, 2); // 컴파일 에러 없음
= 헷갈리는 월 지정
: calendar.set(1582, Calendar.OCTOBER , 4); // 실제로는 9
= 시대에 뒤떨어지는 API : java.util.Data API Doc
getDate()
getDay()
getHours()
# 완전히 새롭게 개발
java.util.Date
java.util.LocalDate
java.util.LocalTime
java.util.LocalDateTime
java.util.ZoneDateTime
# Joda-Time 과 유사한 모습이지만 더 개선된 모습
= 요일 클래스는 Enum 상수로 제공
= 잘못된 월 지정에는 객체 생성 시점에서 DateTimeException을 던진다
= 나노초 단위의 정밀성 등등 ..
Java 8 왜 해야하나?
>[] + []
>“”
>[] + {}
> “{object object}”
>{} + []
>0
>{} + {}
>NaN
결과 예측이 힘들다….

Java8 람다

  • 1.
  • 2.
    패러다임의 변환 GUI 기반의객체지향 프로그래밍 (Web) Text기반의 절차적 프로그래밍 (C/S) 멀티코어 배경의 함수형 프로그램(Big-data)
  • 3.
    # JAVA8 특징 =람다식(Lambda Expression) - 스트림(Stream) API - 기본 메서드(Default Method) = Joda Time 방식의 새 날짜 API 변경 (JSR 310) = 새 자바스크립트 엔진, 나즈혼(Nashorn) = 자바 FX 8 = 메타 데이터 지원 보완 = 동시성 API 개선 = IO/NIO 확장 = Heap에서 영속 세대(Permanent Generation) 제거
  • 4.
    싱글코어 더블코어 # 어떻게? =Thread, Lock, memory model = Thread pool, concurrent collection = Fork / join framework  Functional Programming H/W 에 따른 S/W 개발…
  • 5.
    ‘람다 그거 별것 아닌 것?’ - 그 별것 아닌 것 같은 람다를 오랫동안 자바에서 지원하지 못한 이유?
  • 6.
    람다식(Lambda Expression) = 클래스없이 메서드 정의 수준으로 인자로 전달할 로직을 표현할 수 있는 표기법 = 익명 메서드 (블로저, 블록) Collections.sort(theListOfMyClasses, new Comparator<MyClass>() { public int compare(MyClass a, MyClass b) { return b.getValue() - a.getValue(); } }); theListOfMyClasses.sort((MyClass a, MyClass b) -> { return a.getValue() - b.getValue(); }); theListOfMyClasses.sort((a, b) -> a.getValue() - b.getValue()); 람다 매개변수 -> 람다 본문 = 매개변수의 타입을 추론 = 자바의 if, for 문 등 블럭을 생략 = return 구문도 제거 = 매개변수가 하나 뿐이라면 괄호도 생략 가능
  • 7.
  • 8.
    자바에서 람다식이 필요한이유 (1) 외부 이터레이션과 내부 이터레이션 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); for (int number : numbers) { System.out.println(number); } numbers.forEach(new Consumer<Integer>() { //이름뿐인 내부 클래스 생성 public void accept(Integer value) { System.out.println(value); } }); Numbers.forEach((Integer value) -> System.out.println(value)); // 매개변수 -> 몸체 numbers.forEach(value -> System.out.println(value)); //인수 타입 추론 numbers.forEach(System.out::println); // :: method reference
  • 9.
    자바에서 람다식이 필요한이유 (2) 값만 전달하는 대신 작동 방식도 전달하기 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); public int sumAll(List<Integer> numbers) { int total = 0; for (int number : numbers) { total += number; } return total; } public int sumAllEven(List<Integer> numbers) { int total = 0; for (int number : numbers) { if (number % 2 == 0) { total += number; } } return total; } public int sumAll(List<Integer> numbers, Predicate<Integer> p) { //고차(high order) 함수 int total = 0; for (int number : numbers) { if (p.test(number)) { total += number; } } return total;} sumAll(numbers, n -> true); sumAll(numbers, n -> n % 2 == 0); sumAll(numbers, n -> n > 3);
  • 10.
    자바에서 람다식이 필요한이유 (3) 지연 연산(laziness) 을 통한 효율성 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); for (int number : numbers) { if (number % 2 == 0) { int n2 = number * 2; if (n2 > 5) { System.out.println(n2); break;} } } public boolean isEven(int number) { return number % 2 == 0; } List<Integer> l1 = new ArrayList<Integer>(); for (int n : numbers) { if (isEven(n)) l1.add(n); } List<Integer> l2 = new ArrayList<Integer>(); for (int n : l1) { l2.add(doubleIt(n)); } System.out.println(l2.get(0)); System.out.println( numbers.stream() .filter(Lazy::isEven) .map(Lazy::doubleIt) .filter(Lazy::isGreaterThan5) .findFirst() );
  • 11.
    자바에서 람다식이 필요한이유 (4) 빌려쓰기(loan) 패턴 public class Resource { public Resource() { System.out.println("Opening resource"); } public void operate() { System.out.println("Operating on resource"); } public void dispose() { System.out.println("Disposing resource"); } } Rsource resource = new Resource(); resource.operate(); resource.dispose(); Resource resource = new Resource(); try { resource.operate(); } finally { resource.dispose(); } public static void withResource(Consumer<Resource> consumer) { Resource resource = new Resource(); try { consumer.accept(resource); } finally { resource.dispose(); } } withResource(resource -> resource.operate());
  • 12.
  • 13.
    함수형 프로그래밍(Functional Programming) X1R1 Input  output A 10 Input  output A 10 Input  output A 10 10분 후~ 10년 후~ # Function? X2 -> R1?
  • 14.
    함수형 프로그램(Functional Program)의 특징 # 불변성 (Immutable) : 객체의 상태가 불변 int n = 10; private static final n = 100; //불변 # 참조 투명성(Referential Transparency) : 함수를 호출하는 부분을 그 함수가 반환하는 결과를 대체했을때, 사이드 이펙트가 없는 것 int plusOne(int x) { return x+1; }
  • 15.
    # 1종 객체로서의함수 (First-Class Function) = 함수(또는 메서드)를 값으로 취급함수 파라미터로 넘길 수 있고, 리턴값으로도 사용할 수 있으며, 변수에도 할당할 수 있고, 런타임에도 생성될 수 있다는 의미 = 람다표현식과 메서드레퍼런스 기능으로 보다 효율적으로 인자값으로 취급 가능 (cf. 자바7 인터페이스와 익명클래스를 이용하여 인자 값으로 취급) - int someFunction(another function) - Function someFunction(int i) - list= [function, function2, function3] 함수형 프로그램(Functional Program) 의 특징
  • 16.
    # 선언적 프로그래밍(DeclarativeProgramming) = 함수형 프로그래밍은 함수간의 속성과 관계를 선언하여 최종 결과를 계산하는 것을 방법을 기술. cf. 객체지향 프로그래밍은 프로그램이 절차적인 상태에 따라 '어떤 방법으로 동작' 해야하는지 기술하는 명령형 프로그램. 함수형 프로그램(Functional Program) 의 특징
  • 17.
    기본 메서드(Default Method) =문제점 : 인터페이스에 메서드를 추가하면 하위 호환성이 깨지기 때문에 해당 인터페이스를 구현한 모든 클래스에 새로 추가된 메서드를 구현하고 이 인터페이스를 사용하는 모든 코드가 새로 컴파일 필요 = 기본 메서드 개념 추가 : 하위 호환성 문제없이 인터페이스에 새로운 메서드를 추가할 수 있게 됨 = 기본 메서드란 인터페이스에 구현된 메서드로서 인터페이스를 구현하는 클래스가 오버라이드 하지 않을 경우 기본 구현물로 적용 //JAVA 8 이전 public interface TestInterface { public void action(){ System.out.println("Test"); } } //Abstract methods do not specify a body! //인터페이스의 Abstract Method들에 대한 기본기능을 지정 public interface Student { default void readBook(){ System.out.println("reading book"); } } public class GoSam implements Student { public static void main(String ar[]){ GoSam gosam = new GoSam(); gosam.readBook(); } }
  • 18.
    새 날짜 API #JDK 기존 날짜, 시간 클래스의 문제점 = 불변 객체가 아니다(not immutable) : Calendar 객체나 Date 객체가 여러 객체에서 공유되면? = int 상수 필드의 남용 : calendar.add(Calendar.SECOND, 2); // 컴파일 에러 없음 = 헷갈리는 월 지정 : calendar.set(1582, Calendar.OCTOBER , 4); // 실제로는 9 = 시대에 뒤떨어지는 API : java.util.Data API Doc getDate() getDay() getHours() # 완전히 새롭게 개발 java.util.Date java.util.LocalDate java.util.LocalTime java.util.LocalDateTime java.util.ZoneDateTime # Joda-Time 과 유사한 모습이지만 더 개선된 모습 = 요일 클래스는 Enum 상수로 제공 = 잘못된 월 지정에는 객체 생성 시점에서 DateTimeException을 던진다 = 나노초 단위의 정밀성 등등 ..
  • 19.
    Java 8 왜해야하나? >[] + [] >“” >[] + {} > “{object object}” >{} + [] >0 >{} + {} >NaN 결과 예측이 힘들다….