O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

자바 8 스트림 API

10.749 visualizações

Publicada em

Java 8 Steam API

Publicada em: Software
  • for 루프를 사용한 것과 성능은 비슷하다. 다른 점은 구현이 노출되어 있는 row level 코드를 stream을 사용하여 쉽고 간결하게 표현해 준다는게 다른 점.
    물론 병렬 스트림을 사용하면 성능은 빨라진다.
       Responder 
    Tem certeza que deseja  Sim  Não
    Insira sua mensagem aqui

자바 8 스트림 API

  1. 1. Java 8 Stream API A differentway to process collections 09:18:24
  2. 2. 09:19:27 HTTP://starplatina.tistory.com dosajun@gmail.com @sleepJune 김제준
  3. 3. 나즈혼 람다 기본메서드 STREAM API 날짜API 동시성개선 Base 64 메타프로그래밍향상 자바스크립트엔진 2014.3현재버전8.25 09:18:25
  4. 4. ListtransactionIds =newArrayList(); for(Transactiont :groceryTransactions) { transactionIds.add(t.getId()); } Collections.sort(groceryTransactions, newComparator() { publicintcompare(Transactiont1, Transactiont2) { returnt2.getValue().compareTo(t1.getValue()); } }); ListgroceryTransactions =newArrayList(); for(Transactiont :groceryTransactions) { if(t.getType() ==Transaction.GROCERY) { groceryTransactions.add(t); } } Java 코드로구매내역구하기 식료품점에서구매한걸찾고 사용금액순으로정렬한뒤 거래내역의ID를추출 09:18:25
  5. 5. 그럼Database에서는? SELECT id FROM TRANSACTIONS WHERE type = ‘GROCERY’ ORDER BYvalue DESC 별도의작업없이이미등록된집계함수를사용 SUM, MAX, COUNT, AVG등등 09:18:25
  6. 6. ListgroceryTransactions =newArrayList(); for(Transactiont :groceryTransactions) { if(t.getType() ==Transaction.GROCERY) { groceryTransactions.add(t); } } Collections.sort(groceryTransactions, newComparator() { publicintcompare(Transactiont1, Transactiont2) { returnt2.getValue().compareTo(t1.getValue()); } }); ListtransactionIds =newArrayList(); for(Transactiont :groceryTransactions) { transactionIds.add(t.getId()); } 다시한번자바코드 길다! 복잡하다! 코딩해야된다! 09:18:25
  7. 7. 그래서준비했습니다! ListtransactionsIds =transactions.stream() .filter(t ->t.getType() ==Transaction.GROCERY) .sorted(Comparator.comparing(Transaction::getValue).reversed()) .map(Transaction::getId) .collect(Collectors.toList()); 람다표현식 메소드참조 09:18:25
  8. 8. 일반적인스트림의흐름 filter sorted map collect transactions 2.중간작업(Intermediate Operations) PipeLine 1. 데이터소스 3. 종료작업(Terminal Operations) 09:18:25
  9. 9. 중간작업및종료작업 중간작업(Intermediate Operations) •항상스트림을리턴 •Pipeline 형태로연결시킬수잇음 •데이터를처리하기위한로직 •직접처리를시작할수는없음 •오브젝트를리턴하거나, collection 또는void 리턴가능 •Pipeline으로구성된작업을시작 •한번수행되고난후에작업한스트림에재작업불가능 종료작업(Terminal Operations) flatMap map distinct sorted limit peek filter foreach skip toArray reduce collect minmax count anyMatch allMatchnoneMatch firstFind anyFind 09:18:25
  10. 10. 좀더상세히 Id : 1 Value : 100 Id : 3 Value : 80 Id : 6 Value : 120 Id : 10 Value : 50 Id : 7 Value : 40 Stream <Transaction) Id : 3 Value : 80 Id : 6 Value : 120 Id : 10 Value : 50 .filter(t ->t.getType() ==Transaction.GROCERY) Stream <Transaction) Id : 6 Value : 120 Id : 3 Value : 80 Id : 10 Value : 50 .sorted( Comparator.comparing( Transaction::getValue).reversed()) Stream <Transaction) 6 3 10 .map(Transaction::getId) Stream <Integer) 6 3 10 .collect(Collectors.toList()); List<Integer) 09:18:25
  11. 11. Stream API •Java.util.stream •연산의선언적서술 •반복구조캡슐화, 알고리듬분리 •제어흐름추상화 •함수형방식처리: 데이터불변 •지연처리, 대부분의작업을단일반복수행으로처리 •무한연속데이터흐름API •다양한데이터원천지원: 컬렉션, 생성메서드, 파일I/O 등 09:18:25
  12. 12. 컬렉션과스트림 스트림 컬렉션 List Map Set 보관형자료구조 데이터처리추상화 09:18:25
  13. 13. 스트림과컬렉션처리방법의차이 •파이프라이닝(Pipelining) •많은스트림의기능들이스트림자기자신을리턴 •처리작업이체인처럼연결되어큰파이프라인처럼동작하도록함 •내부반복(Internal Iteration) •명시적으로반복작업을수행해야되는컬렉션과달리스트림작업은내부에서처리 09:18:25
  14. 14. 잠시중간정리 1.질의를할데이터소스(Collection 같은)가필요 2.파이프라인을형성하는중간작업(Intermediate Operations) 3.파이프라인을실행하고결과를리턴하는종료작업(Terminal Operations) Stream 을사용하는일반적인3가지내용 09:18:25
  15. 15. java.util.stream •Building Streams •Infinite Streams •Numeric Streams •Filtering •Mapping •Finding and matching •Reducing •Collect 09:18:25
  16. 16. Building Streams Stream<Integer>numbersFromValues =Stream.of(1, 2, 3, 4); int[] numbers ={1, 2, 3, 4}; IntStreamnumbersFromArray =Arrays.stream(numbers); longnumberOfLines =Files.lines( Paths.get(“yourFile.txt”), Charset.defaultCharset()) .count(); Collection, 숫자들, 값목록, 배열, 파일 값목록, 배열에서Stream 생성 파일에서Stream 생성 09:18:25
  17. 17. Infinite Streams Stream<Integer>numbers =Stream.iterate(0, n ->n +10); numbers.limit(5).forEach(System.out::println); // 0, 10, 20, 30, 40 Stream.iterate Stream.generate 09:18:25
  18. 18. Numeric Streams intstatement =transactions.stream() .map(Transaction::getValue) .sum(); // error since Stream has no sum method intstatementSum =transactions.stream() .mapToInt(Transaction::getValue) .sum(); // works! IntStream DoubleStream LongStream mapToInt mapToDouble mapToLong sum(), min(), max(), average(), count() intstatementSum =transactions.stream() .mapToInt(Transaction::getValue) .IntSummaryStatistics(); // IntSummaryStatistics{count=7, sum=28, min=1, average=4.000000, max=7} 09:18:25
  19. 19. Filtering •filter •주어진predicate와일치하는stream을리턴 •distinct •중복을제거한유니크엘리먼트stream을리턴 •limit(n) •주어진사이즈(n) 까지의stream을리턴 •skip(n) •주어진엘리먼트길이까지제외한stream을리턴 09:18:25
  20. 20. Mapping List<String>words =Arrays.asList("Oracle", "Java", "Magazine"); List<Integer>wordLengths =words.stream() .map(String::length) .collect(toList()); map(String::length) 인자로전달받은값들을가지고새로운Stream 생성 List에저장된단어들의길이를가지고있는새로운list 생성 map(e -> e * 2) map(s -> s.toUpperCase()) 09:18:25
  21. 21. Finding and Matching transactions.stream() .filter(t ->t.getType() ==Transaction.GROCERY) .findAny() .ifPresent(System.out::println); booleanexpensive =transactions.stream() .allMatch(t->t.getValue() >100); anyMatch, allMatch, noneMatch Optional<Transaction>=transactions.stream() .filter(t ->t.getType() ==Transaction.GROCERY) .findAny(); findFirst, findAny java.util.Optional 09:18:25
  22. 22. Reducing intsum =0; for(intx :numbers) { sum +=x; } intsum =numbers.stream().reduce(0, (a, b) ->a +b); intproduct =numbers.stream().reduce(1, (a, b) ->a *b); intproduct =numbers.stream().reduce(1, Integer::max); for loop 를활용한덧셈 초기화값: 0 BinaryOperator<T> : 두개의엘리멘트를더해새로운값을생성 모든값을곱하기 최대값구하기 엘리먼트들을하나의결과로추출 09:18:25
  23. 23. Collect 09:18:25 List<Person>filtered =persons .stream() .filter(p ->p.name.startsWith("P")) .collect(Collectors.toList());// Collectors.toSet() System.out.println(filtered); // [Peter, Pamela] Map<Integer, List<Person>>personsByAge =persons .stream() .collect(Collectors.groupingBy(p ->p.age)); personsByAge .forEach((age, p) ->System.out.format("age %s: %sn", age, p)); // age 18: [Max]// age 23: [Peter, Pamela]// age 12: [David]
  24. 24. 정리 1.Stream API 의다양한기능을활용해데이터처리를최적화할수있다. 2.람다와메서드참조를알아두면더좋음! 3.병렬처리를손쉽게지원 •stream() -> parallelStream() 09:18:25
  25. 25. 참고자료 1.Processing Data with Java SE 8 Streams •http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html 2.Beyond Java : 자바8을중심으로본자바의혁신 •http://www.slideshare.net/gyumee/beyond-java-8 3.java.util.stream •https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
  26. 26. THANKYOU! 09:18:25

×