Java 8

Java 1.8

  • 람다식(Lambda Expression)

  • 스트림(Stream) API

  • 기본 메서드(Default Method)

  • 새 자바스크립트 엔진, 나즈혼(Nashorn)

  • Joda Time 방식의 새 날짜 API 변경 (JSR 310)

  • 자바 FX 8

  • 메타 데이터 지원 보완

  • 동시성 API 개선

  • IO/NIO 확장

  • Heap에서 영속 세대(Permanent Generation) 제거 

출처

람다 (Lambda)

 함수형 인터페이스

( Functional Interface )

- 추상 메소드가 하나뿐인 메소드

Runnable

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
public class AsyncHelloWorld {

	public static class HelloWorld implements Runnable {

		@Override
		public void run() {
			System.out.println("Hello World");
		}
		
	}
	
	public static void main(String[] args) {
		new Thread(new HelloWorld()).start();
	}
}
new Thread(new Runnable() {
	@Override
	public void run() {
		System.out.println("Hello World");
	}
}).start();

Java 1.7

Java 1.8

new Thread(()-> System.out.println("Hello World")).start();

타입 추론

문법식

 

[ 표현 ] 람다 매개변수  ->  람다 본문

( 인자 목록 ) -> { 구문 } 

new Thread(()-> System.out.println("Hello World")).start();

Runnable r1 = () -> System.out.println("I am running");

(int n, String str) -> { return str + n }
(int n, String str) -> str + n
(n, str) -> str + n
() -> "Hello World!"
() -> {}

요약

  • 함수형 인터페이스
  • 람다 매개변수  ->  람다 본문
  • 람다식 = 익명 메소드
  • 대상 타입
  • 매개변수 타입  추론
  • 다양한 축약형 람다식

Stream API

Collection

  • 외부 반복(External Iteration)

  • 반복을 통해 생성

  • 효율적이고 직접적인 요소 처리

  • 유한 데이터 구조

  • 반복적 재사용 가능 

Stream

  • 내부 반복(Internal Iteration)
  • 반복을 통해 연산
  • 파이프-필터 기반 API
  • 무한 연속 흐름 데이터 구조
  • 재사용 불가 
for(int n : numbers) {
    ..
}
numbers.forEach(n -> .. )

Stream API 목적

데이터 보관이 아닌

데이터 처리에 집중

중계연산

Stream<T> filter ( T -> boolean )

- 조건에 만족하는 요소로 구성된 스트림을 얻을 때

- 각 요소를 확인해서 조건을 통과한 요소만으로 새 스트림 생성

- 참/거짓을 반환하는 조건식을 인수로 전달

Stream<R> map(T -> R)

- 스트림에 있는 값들을 변환하고 싶을 때

- T타입의 요소를 1:1로 R 타입의 요소로 변환 후 스트림 생성

- 변환을 처리하는 함수를 인수로 전달

최종연산

- 최종 연산이기 때문이 이후 스트림을 사용할 수 없음

void forEach(T -> void)

- 각 요소를 인수로 전달된 함수에 전달해 처리

summaryStatistics()
- [Int, Long, Double]SummaryStatistics summaryStatistics() 
- 합계, 평균, 최소값, 최대값, 개수에 대한 요약 통계

sum() | average() | min() | max()
- 합계 - [int, long, double] sum()
- 평균 - OptionalDouble average()
- 최소값 - Optional[Int, Long, Double] min()

- 최대값 - Optional[Int, Long, Double] max()

Collectors: 공통 컬렉터용 팩토리 메소드를 제공

 

// Collection 타입으로 요소를 모을 때 
contacts.stream().collect(Collectors.toList()); 
contacts.stream().collect(Collectors.toSet()); 
contacts.stream().collect(Collectors.toCollection(TreeSet::new));

// Map 타입으로 요소를 모을 때 
contacts.stream().collect(Collectors.toMap( Contact::getName, Contact::getBirthday));
 contacts.stream().collect(Collectors.toMap( Contact::getName, Function.identity()));

//스트림에 있는 모든 문자열을 서로 연결해서 모을 때 
contacts.stream().map(Contact::getName).collect(Collectors.joining()); 
contacts.stream().map(Object::toString).collect(Collectors.joining("|"));

키워드 목록에서 "광고중핫딜" 키워들 제외 후 소문자로 변환한 데이터가 필요

List<String> keywords = ..

List<String> results = new ArrayList<String>();

for(String keyword : keywords) {
    
    if(!"광고중핫딜".equals(keyword)) {
        results.add( keyword.toLowerCase());
    }

}

return results;
keywords.stream()
    .filter(k -> !"광고중핫딜".equals(k))
    .map(k -> k.toLowerCase())
    .collect(Collectors.toList());
List<HotTopic> items = new ArrayList<HotTopic>();

String keywords = "";
int size = items.size();

for(int i = 0; i < size; i++) {
	HotTopic item = items.get(i);

	if(i != 0 ) {
		keyword += ", " + item.getKeyword();
	} else {
		keyword = item.getKeyword();
		i++;
	}
	
}
String keywords = items.stream()
                    .map(item -> item.getKeyword())
                    .collect(Collectors.joining(","));

핫토픽 목록에서 키워드만 뽑아서 하나의 문자로 반환 

File I/O Stream

java.nio.file.Files

FileChannel channel = null;
MappedByteBuffer byteBuffer = null;
Scanner scanner = null;

try {
    List<String> results = new ArrayList<String>();
			
    channel = new FileInputStream(LOG_FILE).getChannel();
    byteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
    CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
    CharBuffer charBuffer = decoder.decode(byteBuffer);
    scanner = new Scanner(charBuffer).useDelimiter("\n");

    int i = 0;
    while(scanner.hasNext()) {
        String text = scanner.next();
	String[] words = text.split(",");
	String txt = words[0];

	if(!results.contains(txt)) {
            if(i == 100) break;

            results.add(txt);
            i++;

            System.out.println(txt);
        }
    }
} catch(IOException e) {
    ..
}
Files.lines(Paths.get(LOG_FILE))
    .map(text -> {
        String[] words = text.split(",");
        String txt = words[0];
        return txt;
    })
    .distinct()
    .limit(100)
    .forEach(System.out::println);

요약

- 스트림 라이브러리 
: 컬렉션 프레임워크보다 한 단계 더 높은 추상화된 API 
: 내부 반복을 통해 제어 흐름 추상화하고 최적화와 알고리즘을 분리
- 스트림 연산 
: 중개 연산 / 파이프와 필터, 맵(Map)  

: 최종 연산 / 결과 생산(Reduce)
- 지연 연산을 통한 성능 최적화
- 병렬 처리 추상화를 통한 손쉬운 사용
- 컬렉션 외 다양한 연속적 데이터에 사용

참고

Q & A

 

2015년 수고 많으셨습니다~

deck

By Ilhyun Seo

deck

  • 292