Download - SpringCamp 2013 : About Jdk8
이 문서는 나눔글꼴로 작성되었습니다. 설치하기
Home : GodOfJava.com Blog : tuning-java.com
이상민
JDK 8에
추가된 것들은?
목차
1. Introduction
2. JDK 7 Summary
3. JDK 8 Summary
4. java.time
5. Lambda Expression
6. Bulk Data Operation
7. Conclusion
JDK 7 Summary
1. JDK 7 에서 변경된 것들
추가 사항
- 숫자 표시 방법 보완
- switch 문에서 String 사용
- 제네릭을 쉽게 사용할 수 있는 Diamond
- 예외처리시 다중처리 가능
6
2. JDK 7 에서 추가된 것들
추가 사항
- Fork Join
- NIO2
- JDBC 4.1
- TransferQueue 추가
- Objects 클래스 추가
7
JDK 8 Summary
1. JDK 8 Download
JDK 8 은 2013년 10월 현재 EA (Early Access)
- 정식 버전은 아직 나오지 않았으며 2014년 중에는 나올 듯
다운로드는 아래 링크에서
- https://jdk8.java.net/download.html
- 잘 안받아짐. 계속 끊김 !!!
(Safari에서 계속 다시 다운로드를 누르면서 받거나 다운로드 툴 권장)
9
2. Full added features
추가된 기능들 목록
(http://openjdk.java.net/projects/jdk8/features)
10
3. Today …
오늘 다룰 내용은
- java.time package
- Lambda Expression
- Bulk Data Operation
참고
- 모듈화 부분을 담당하는 jigsaw 는 JDK 8에서 제외 되었음
11
java.time
Date-Time API
1. About Date-Time API
Data-Time API
- JDK 8 부터 제공되며, ISO-8601 표준을 따름
(http://www.iso.org/iso/home/standards/iso8601.htm)
- 모든 클래스는 immutable 하고, thread safe
- Hijrah(Islamic), Japanese, Minguo(Taiwan), ThaiBuddhist 달력을 제공
안타깝게도 우리나라의 음력은 존재하지 않음
13
2. Date-Time Design Principles
Clear
Fluent
Immutable
Extensible
14
2. Date-Time Design Principles
Clear
- API를 명백하게 만들었음
- 예를 들어 매개변수로 null이 들어오면 NullPointerException 발생
Fluent
- 코드를 읽기 쉽게
Immutable
- 불변의 객체
Extensible
- 임의의 달력을 쉽게 추가 할 수 있음
15
LocalDate today = LocalDate.now(); LocalDate payday = today.with(TemporalAdjuster.lastDayOfMonth()).minusDays(2);
LocalDate dateOfBirth = LocalDate.of(2012, Month.MAY, 14); LocalDate firstBirthday = dateOfBirth.plusYears(1);
3. Date-Time packages
java.time
java.time.chrono
java.time.format
java.time.temporal
java.time.zone
16
3. Date-Time packages
java.time
- 날짜와 시간을 나타내는 코어(core) API
java.time.chrono
- 주요 달력 제공
java.time.format
- 날짜를 format하고 parse하는 클래스 제공
java.time.temporal
- 날짜 및 시간 클래스들을 처리하기 위한 확장 API
java.time.zone
- 타임존(time zone) 지원 클래스들
17
4. Naming Convention
주요 메소드이름 prefix
18
Prefix Method type Description
of static factory
입력 매개변수에 따라 인스턴스 생성
from static factory
입력 매개변수를 대상 클래스로 변환
parse static factory
입력 문자열을 파싱하여 대상 클래스의 인스턴스 생성
format instance 지정된 formatter를 사용하여 값을 format
get instance 대상 객체의 일부 상태 값을 리턴
is instance 대상 객체의 상태 확인
with instance 하나의 요소가 변경된 복제 객체 리턴
plus instance 하나의 요소를 더한 복제 객체 리턴
minus instance 하나의 요소의 값을 뺀 복제 객체 리턴
to instance 현재 객체를 다른 타입으로 변환
at instance 현재 객체를 다른 객체와 결합
Lambda Expression
1. About Lambda
Lambda Expression
- “람다 익스프레션”이라고 발음.
(무식하게 “람브다”라고 읽지 말 것 !)
- 이건 뭐 그냥 간단한 표현식을 배우는 것이라기 보다는
새로운 언어를 배우는 느낌 ?
- .stream().filter(…).map() 과 같이 .을 계속 찍어주는 문법에 익숙해도 30%는
먹고 들어가는 것
- 익명(Anonymous) 클래스만 이해해도 20%는 먹고 들어가는 것
- 화살표(->)와 땡땡(::)만 잘 이해해도 40%은 먹고 들어가는 것
- 나머지 10%는 API 를 이해하는 것
- 오늘 이 시간에 모두 이해하기 쉽지 않은 것 20
1. About Lambda
Lambda Expression 예
21
Stream.of(idArray) .map(EmployeeUtils::findById) .filter(e -> e !=null) .filter(e -> e.getSalary() > 50000) .findFirst() .orElse(null);
2. Basic Knowledge
Lambda Expression 을 알아보기 전에 샘플을 이해하기 위한 API 이해
java.util.Comparator interface의 compare() 메소드
java.util.Arrays class의 sort() 메소드
22
3. Understand Lambda-1
다음의 Integer 를 정렬해 보자.
Arrays.sort(T[] t) 메소드를 사용할 수도 있지만, Comparator를 사용해야 하는
상황일 경우 Comparator 인터페이스를 구현해야 ~~~
23
Integer[] data={3,2,1,4,6,5,9,8,7,10};
3. Understand Lambda-1
Comparator 인터페이스를 구현한 Integer 비교 클래스
24
class IntegerComparator<T> implements Comparator<T> { @Override public int compare(T x,T y) { if(x instanceof Integer) { return compareInt((Integer)x,(Integer)y); } else return 0; } public int compareInt(Integer x,Integer y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } }
방법 1
3. Understand Lambda-1
IntegerComparator 클래스 사용 예
25
public void useClass(Integer[] data) { IntegerComparator<Integer> compare=new IntegerComparator<Integer>(); Arrays.sort(data,compare); for(Integer temp:data) { System.out.println(temp); } }
방법 1
3. Understand Lambda-1
방법 2 부터는 compareInt() 메소드가 해당 클래스에 선언 되어 있을 경우
26
public int compareInt(Integer x,Integer y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); }
3. Understand Lambda-1
Anonymous 클래스 사용 예
27
public void anonymous(Integer[] data) { Comparator<Integer> compare=new Comparator<Integer>() { @Override public int compare(Integer x,Integer y) { return compareInt(x,y); } }; Arrays.sort(data,compare); for(Integer temp:data) { System.out.println(temp); } }
방법 2
3. Understand Lambda-1
Lambda 사용 예 1
28
public void lambda1(Integer[] data) { Arrays.sort(data, (Integer x,Integer y) -> compareInt(x,y) ); for(Integer temp:data) { System.out.println(temp); } }
방법 3
3. Understand Lambda-1
Lambda 사용 예 2
29
public void lambda2(Integer[] data) { Arrays.sort(data, (x,y) -> compareInt(x,y) ); for(Integer temp:data) { System.out.println(temp); } }
방법 4
3. Understand Lambda-1
Lambda 사용 예 3
30
public void lambda3(Integer[] data) { List<Integer> list=Arrays.asList(data); list.sort( (x,y) -> compareInt(x,y) ); list.forEach(System.out::println); }
방법 5
4. Understand Lambda-2
Lambda 사용 예
31
public class Calculator { interface IntegerMath { int operation(int a, int b); } public int operateBinary(int a, int b, IntegerMath op) { return op.operation(a, b); } public static void main(String... args) { Calculator myApp = new Calculator(); IntegerMath addition = (a, b) -> a + b; IntegerMath subtraction = (a, b) -> a - b; System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition)); System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction)); } }
4. Understand Lambda-2
Lambda 사용 예
32
public class Calculator { interface IntegerMath { int operation(int a, int b); } public int operateBinary(int a, int b, IntegerMath op) { return op.operation(a, b); } public static void main(String... args) { Calculator myApp = new Calculator(); IntegerMath addition = (a, b) -> a + b; IntegerMath subtraction = (a, b) -> a - b; System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition)); System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction)); } }
4. Understand Lambda-2
Lambda 사용 예
33
public class Calculator { interface IntegerMath { int operation(int a, int b); } public int operateBinary(int a, int b, IntegerMath op) { return op.operation(a, b); } public static void main(String... args) { Calculator myApp = new Calculator(); IntegerMath addition = (a, b) -> a + b; IntegerMath subtraction = (a, b) -> a - b; System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition)); System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction)); } }
4. Understand Lambda-2
Lambda 사용 예
34
public class Calculator { interface IntegerMath { int operation(int a, int b); } public int operateBinary(int a, int b, IntegerMath op) { return op.operation(a, b); } public static void main(String... args) { Calculator myApp = new Calculator(); IntegerMath addition = (a, b) -> a + b; IntegerMath subtraction = (a, b) -> a - b; System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition)); System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction)); } }
5. Expression
-> (arrow token)
- 매개변수로 a와 b 를 받는 작업을 addition 객체에 할당한다.
- (a,b)에서 매개변수 타입을 명시해도 되고, 명시하지 않아도 된다.
35
IntegerMath addition = (a, b) -> a + b;
IntegerMath addition = (int a, int b) -> a + b;
5. Expression
:: (method reference)
- 람다 문장이 들어가는 부분에 :: 을 사용하여 메소드 참조 가능
- 메소드 참조 문법은 아래와 같음
36
System.out::println
Kind Example
static 메소드 참조 클래스명::static메소드명
인스턴스 메소드 참조 인스턴스명::메소드명
특정 타입의 인스턴스 메소드 참조 타입::메소드명
생성자 참조 클래스명::new
Bulk Data Operation
java.util.stream.Stream
1. Stream interface
java.util.stream.Stream interface
- Collection API를 구현 / 확장한 클래스의 객체를 쉽게 처리할 수 있도록 한 인
터페이스
- http://download.java.net/jdk8/docs/api/
- Collection 클래스의 stream() 메소드를 호출하면 Stream 객체 생성
- Steam == sequence of elements
38
1. Stream interface
변환 대상 객체
Stream interface 예
39
public void map(List<Integer> numbers) { System.out.println("map()"); numbers.stream() .map(value -> value *2) .forEach(System.out::println); }
List<Integer> numbers=Arrays.asList(1,2,3,4,5,6,7,8,9,10);
2. Stream methods
주요 메소드
40
Method Description
filter(Predicate<T> predicate) 주어진 조건(predicate)에 맞는 요소 리턴
forEach(Consumer<T> action) 주어진 작업(action) 실행
map(Function<T,R> mapper) 수행된 작업(mapper)의 결과를 리턴
reduce(BinaryOperator<T> accumulator)
reduce 작업 수행 (항상 새로운 객체 및 값을 리턴)
collect(Collector<? super T,A,R> collector)
mutable reduction 작업 수행(수정된 객체 및 값을 리턴)
3. Stream 예
filter & forEach
41
numbers.stream() .filter(value -> value %3 == 0) .forEach(System.out::println);
3. Stream 예
map & forEach
42
numbers.stream() .map(value -> value *2) .forEach(System.out::println);
3. Stream 예
reduce
43
List<String> names= Arrays.asList("God","Of","Java","You","Min","Yeon","Sook"); Optional<String> shortestName = names.stream() .reduce((name1,name2) -> name1.length()<=name2.length() ? name1 : name2 ); Optional<String> longestName = names.stream() .reduce((name1,name2) -> name1.length()>=name2.length() ? name1 : name2 ); System.out.println(shortestName.get()); System.out.println(longestName.get());
Conclusion
Conclusion
설명한 내용이 이해 안된다고 좌절하지 말자 !
- 어차피 JDK 8 Release는 내년
이해할 시간은 충분하다.
- 어차피 Release 된 이후에 여러분들의 시스템에서 JDK 8을 사용하려면 멀었다.
이해할 시간은 더 충분하다.
그렇다고 Lambda Expression 무시하면 ?
- 3년 뒤에 도태된다.
코드를 이해 못하겠죠?
45
Conclusion
오늘 설명한 내용은 빙산의 일각일 뿐
- Lambda 및 Bulk Data Operation 에 대해서 자세히 살펴보려면 API/Java Tutorial
참고
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
http://docs.oracle.com/javase/tutorial/collections/streams/index.html
46
* Lambda reference
State of the Lambda
- http://cr.openjdk.java.net/~briangoetz/lambda/lambda-libraries-final.html
Java Tutorial
- http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Slideshare
- http://www.slideshare.net/scottleber/java8-8-lambda-expressions
Marty Hall (slideshare)
- http://www.slideshare.net/martyhall/java-8-tutorial-streams-part-1
- http://www.slideshare.net/martyhall/java-8-tutorial-streams-part-2-map-
reduce-parallel-streams-and-infinite-streams
- http://www.slideshare.net/martyhall/java-8-tutorial-lambda-expressions-
part-1
- http://www.slideshare.net/martyhall/java-8-tutorial-lambda-expressions-
part-2
- http://www.slideshare.net/martyhall/java-8-tutorial-lambda-expressions-
part-3
47
감사합니다.
이 문서는 나눔글꼴로 작성되었습니다. 설치하기