F,P,S & FunctionalInterface

java8~ 2016. 10. 23. 11:20

  

java 8 경험자 Tip:   REF-SITE ,  http://okky.kr/article/357825  


 

1. Object리턴시에  null처리가 쉽도록, Optional.ofNullable() 사용.

   예제)  

           Optional<Soundcard> soundcard = Optional.ofNullable(mabyeSoundcard); 
           if(soundcard .isPresent())

   System.out.println (soundcard.get()); //get Real Value from Optional

또는

soundcard.ifPresent(System.out::println); 도 OK.

soundcard.ifPresent(card -> map.put(card)); 도 가능.


      Soundcard soundcard = mabyeSoundcard.orElse(new Soundcard("defaut"));

- orElseThrow(IllegalStateException::new); 도 가능

 

Optional.map(s->s.getID()).orElse()도 굿.  orElseGet( blabla) 도 있음. 

Optional.flatMap : content가 또 Optional일경우 벗김-  REF2번참조


 

2.  mutable인 String[]리턴 대신에, immutable인 Stream<String> 리턴.  REF-SITE

  

Stream<String> words = Stream.of("Java", "Magazine", "is", "the", "best");

or

Stream<String> words = Arrays.stream(arrOfStr); //String[] arrOfStr = {"A","BB"}

 

 

   예제) "hey duke".chars().forEach (c -> System.out.println((char)c));

           Stream<Character> sch = "abc".chars().mapToObj(i -> (char)i);     (char)가 Character로 autobox됨.


 

3. Function Reference & Predicate Reference. (함수의 파라미터로도 넘길 수 있게 됨)

   

   Predicate의 경우 scala와 거의 유사한 방식으로. boolean리턴하는 method define후, 이 것들을 넘길 수 있음. 

 


  Function<String, Integer> f = Integer::parseInt;
  Integer result = f.apply("123");

 

  Predicate<String> p = str::equals;
  p.test("world");

 

 Supplier< > s = 

 s. get(); 

 


 4. interface  : 기존 interface를 좀 다르게 FunctionalInterface로 사용가능. @FunctionalInterface 도 존재.

   => 이걸 파라미터로 넘길수도 있다.  (function도 넘길 수 있듯이)  : 음 class도 넘길수 있으니 당연한 건가..

   

    FunctionalInterface REF -> abstract Method는 한개만 존재

    javaInAction8책에서는 Validator Strategy및 8.2장 참조.




Posted by yongary
,