[스터디할래? Java] 목차
이글은 백기선님 스터디 할래? 스터디를 뒤늦게 따라간 기록입니다.
스터디할래 링크 >> https://github.com/whiteship/live-study
이필기를 시작으로 공부했습니다 >>https://xxxelppa.tistory.com/207, https://tourspace.tistory.com/6
여기 없는내용은 스터디 할래 강의 내용 혹은 제가 java Doc보고작성하거나 예제를 만들어 추가했습니다.
그외는 같이 출처가 써있습니다.
람다식 | lambda expression : 식별자 없이 실행 가능한 함수표현식 익명클래스를 함수표현식으로 처리할수 있음. 식별자: 코드에 존재하는 변수, 자료형, 서브루틴 등을 가리키는 토큰이다. + java8 부터 람다식 가능하게한것은 함수형프로그램이 가능하게 하기위해. 함수 자체가 first-class-function : 변수할당, 매개변수 전달, 리턴 전달 가능해짐. 컬렉션 잘쓰려고 스트림 지원, 그를위해 함수형 프로그래밍 지원, 그를위해 람다 지원. + 익명내부클래스는 XXXXXX$1.class 로 컴파일 됨. 람다는 invoke dynamic(jdk1.7, 인디) 이라는 opcode 사용. 바이트트 코드 확인가능 이런이유로 버전올라갈때 개선의 여지가 있다고함. invoke dynamic : (jdk1.7, 인디) 동적타입언어. 바이트 코드 셋. -기존 4가지 invokevirtual(instance메소드 디스패치), invokestatic, invokeinterface, invokespecial -메소드이름, 메소드시그니처, 메소드 정의 클래스, 메소드 실행 바이트 코드 가 명확히선언필요... invoke dynamic : https://tourspace.tistory.com/12 + 람다를 지연연산으로 활용할수 있다. |
Variable Capture | 변수 캡쳐 람다 외부 정의된 변수 : 자유변수 :Free Valiable 자유변수를 참조 : 람다 캡쳐링 :Lambda Capthuring 람다에서 지역변수 참조시 : 1. final, 2. final처럼 동작 ==> 재할당 안되야. 원인 : 지역변수 스택생성 쓰레드끼리 공유 안된다. 인스턴스변수 힙영역생성, 쓰레드 공유가능. 람다는 변수도 자신의 스택에 저장해서 쓰는데 변하면안된다는 제약조건 필요한이유. https://perfectacle.github.io/2019/06/30/java-8-lambda-capturing/ + VariableCapture 클래스. run 메서드 안에 익명클래스는다른영역 -->(익명내부클래스 쉐도잉 = 새로운 scop 를 가짐, 동일변수선언가능). run 메서드 안에 람다는 같은 scope 같은 이름 변수 정의 불가. |
메소드 생성자 레퍼런스 | " :: " 1. static 메소드참조 클래스이름::메소드이름 System.out::println 2. 인스턴스메소드참조 3. 람다식 매개변수로 접근가능 메소드참조 BiFunction<string,string,boolean> stringContain = String::contains; System.out.println(stringContain.apply("apple","a")); 4. 생성자 참조 클래스이름 :: new Supplier<Random> random = Random::new; System.out.println(random.get().nextInt(10)+1); |
타입추론 | Predicate<String> isEmpty = s-> s==null || s.length()<0; |
함수형 인터페이스 | |
함수형 인터페이스 @FunctionalInterface |
추상메서드가 하나뿐인인터페이스 Consumer,Runnable, Predicate, supplier, functon..... |
Runnable | Runnable runnable = new Runnable() { @Override public void run() { System.out.println("Run"); } }; Runnable lambdaRun = ()->{System.out.println("run");}; new Thread(lambdaRun).start(); |
predicate<T> | boolean test(T t); List<Integer> numbers = new ArrayList(); numbers.add(3); numbers.add(1); numbers.add(0); numbers.add(2); Predicate<Integer> moreThen3 = (num) -> num >= 3; System.out.println(moreThen3.test(4)); numbers.removeIf(moreThen3); String num = numbers.stream().map(Object::toString).collect(Collectors.joining(",")); System.out.println(num); https://zetcode.com/java/predicate/ List<VerseModel> verses = chapter.getBibleVerse().stream().filter(verse -> verse.getBiblePublish().getPublishSn() ==publishesSn.get(0)).collect(Collectors.toList()); |
Consumer<T> https://zetcode.com/java/consumer/ |
void accept(T t); List<Integer> numbers = new ArrayList(); numbers.add(3); numbers.add(1); numbers.add(0); numbers.add(2); Consumer<List> toStringList = (list) -> { System.out.println(list.stream().map(Object::toString).collect(Collectors.joining(",")));; }; toStringList.accept(numbers); |
ArrayList.forEach(Consumer<? super E> action) List<Integer> numbers = new ArrayList(); numbers.add(3); numbers.add(1); numbers.add(0); numbers.add(2); numbers.forEach((num)->{System.out.println(String.valueOf(num));}); |
|
Consumer.andThen(Consumer<? super T> after) Consumer<List<String>> addRoom = (list) -> { for (int i = 0; i < list.size(); i++) { list.set(i,list.get(i).concat(" Room")); } }; Consumer<List> toStringList = (list) -> { System.out.println(list.stream().map(Object::toString).collect(Collectors.joining(",")));; }; List<String> strNum = new ArrayList<>(); strNum.add("a"); strNum.add("B"); strNum.add("C"); strNum.add("d"); addRoom.andThen(toStringList).accept(strNum); |
|
Consumer<T>, BiConsumer<T,U>, DoubleConsumer, IntConsumer, LongConsumer, ObjDoubleConsumer, ObjIntConsumer, ObjLongConsumer | |
Supplier<T> |
T get(); Supplier random10Supplier = ()-> new Random().nextInt(10)+1; Stream.generate(random10Supplier).limit(5).forEach(System.out::println); System.out.println(random10Supplier.get()); https://java2blog.com/java-8-supplier-example/#Java_8_Supplier_example |
Supplier<T>, BooleanSupplier, DoubleSupplier, IntSupplier LongSupplier | |
Function<T,R> | R apply(T t); Function<Integer,Integer> plus4 = (num)-> num + 4; System.out.println(plus4.apply(5)); |
Function<T,R>, BiFunction<T,U,R>, DoubleFunction<R>, IntFunction<R>, IntToDoubleFunction.... List<Integer> publishSnList = publishModelList.stream().map(TheBiblePublishModel::getPublishSn).collect(Collectors.toList()) List<String> verseList = verses.stream().map(verse -> verse.getVerse()).collect(Collectors.toList()); |
|
UnaryOperator<T> | T apply(T t); - Function<T,R> 같은타입일때. UnaryOperator<Integer> UnaryPlus4 = (num)-> num + 4; System.out.println(UnaryPlus4.apply(5)); |
BinaryOperator - BiFunction<T,U,R>, UnaryOperator<T>, DoubleBinaryOperator..... | |
stream from https://futurecreator.github.io/2018/08/26/java-8-streams/ | |
stream | jdk8 람다 활용가능기술 1. 생성 :스트림인스턴스생성 2. 가공 : 필터링, 맵핑, 등 중간작업 3. 결과 |
stream 생성 | 1. 배열 스트림 2. 컬렉션스트림 3. 비어있는스트림 Stream.empty() 4. 빌더스트림 Stream<String> builderStream = Stream.<String>builder().add("A").add("B").add("C").build(); 5. Stream.generate() Stream<String> genStream = Stream.generate(()->"gen").limit(3); System.out.println(genStream.map(String::toString).collect(Collectors.joining()));//gengengen 6. Stream.iterate() Stream<Integer> iterStream = Stream.iterate(1,n->n+1).limit(3); System.out.println(iterStream.map(num-> String.valueOf(num)).collect(Collectors.joining()));//123 7.기본타입, 문자형 스트림. 파일, 병렬 IntStream, LongStream, DoubleStream, .paralleStream() |
stream 가공 | 1. 연결 Stream.concat(stream1,stream2); 2. Filtering -> Stream<T> filter(Predicate<? super T> predicate) Stream<String> stream = name.stream().filter(name-> name.contain("a")); 3. Mapping -> <R> Stream<R> map(Function<? super T, ? extends R> mapper); 4. flatMap -> <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper); List<String> flatList = list.stream() .flatMap(Collection::stream) .collect(Collectors.toList()); // [a, b] 4. sorting() sorted(Comparator.comparingInt(String::length)) 5. peek : 그냥 확인해본다. |
stream 결과 | 1. 연산 스트림.count(), 스트림.sum(), 스트림.min();, 스트림.max() 2. reduce OptionalInt reduced = IntStream.range(1, 4) // [1, 2, 3] .reduce((a, b) -> { return Integer.sum(a, b); }); System.out.println(reduced.getAsInt()); 3. Collecting >> .collect(XXXXXX) - Collectors.toList() 리스트 반환 -Collectors.joining(", ", "<", ">"); - Collectors.averageIngInt(Product::getAmount); 평균 - Collectors.summingInt() 합 - Collectors.summarizingInt(); 합, 평균 - Collectors.groupingBy() 그룹 - Collectors.partitioningBy() Predicate 함수. - Collectors.of() 직접 Collector 만듬 3. Matching .anyMatch(name -> name.contains("a")); 4. foreach : 최종과정의 peek names.stream().forEach(System.out::println); Map<Integer, String> map = list.stream().collect( Collectors.toMap(Item::getId, Item::getValue)); Map<Integer, Boolean> isUsedPublish = publishesSn.stream().collect(Collectors.toMap(Function.identity(), e -> true)); |
** random.nextInt(max - min + 1) + min
추천책 : 시작의 기술 ,
못하는건가... 안하는건가.....
+ 리플렉션. : 가장 빨리 getter를 읽는 방법은?
https://dzone.com/articles/java-reflection-but-faster
- Java Reflection is slow.
- Java MethodHandles are slow too. // MethodHandlers.lookup() jdk7 리플렉션과 별차이없음...
- Generated code with javax.tools.JavaCompiler is fast. //JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
- LambdaMetafactory is pretty fast. //MethodHandles.Lookup lookup = MethodHandles.lookup();
CallSite site = LambdaMetafactory.metafactory(lookup,
제니퍼.
So, the devil is in the details. Let’s go through the implementations to confirm that I applied typical magical tricks, such as
So, the devil is in the details. >>> (A를 B로 합시다)... 구현하면 일이 많아진다.
String[] names = {"Z","B","C"};
Arrays.sort(names,String::compareToIgnoreCase); //(this, o2) -> this.compareTo(o2)
Arrays.stream(names).forEach(System.out::print);
- 람다식 사용법
- 함수형 인터페이스
- Variable Capture
- 메소드, 생성자 레퍼런스
'JAVA > Basic' 카테고리의 다른 글
[스터디할래? Java] 목차 (0) | 2021.05.17 |
---|---|
[스터디할래? Java 14]제네릭 (0) | 2021.05.15 |
[스터디할래? Java 13]I/O (0) | 2021.05.15 |
[스터디할래? Java 12]애노테이션 (0) | 2021.05.15 |
[스터디할래? Java 11]enum (0) | 2021.05.15 |