Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java 8 Puzzlers [as presented at OSCON 2016]

917 views

Published on

We aren't sure about you, but working with Java 8 made one of the speakers lose all of his hair and the other lose his sleep (or was it the jetlag?). If you still haven't reached the level of Brian Goetz in mastering lambdas and strings, this talk is for you. And if you think you have, we have some bad news for you, you should attend as well.

Published in: Software
  • The secret to making your dog's problem behaviors disappear. ★★★ https://tinyurl.com/rrpbzfr
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Java 8 Puzzlers [as presented at OSCON 2016]

  1. 1. whoiam Developer Advocate @JFrog @jbaruch on the internetz
  2. 2. whoiam Solutions Architect @Hazelcast @gAmUssA on the internetz
  3. 3. BTW,
  4. 4. 1. Two entertaining guys on stage 2. Funny Puzzling questions 3. You think and vote 4. Awesome t-shirts fly in the air 5. Official twitter handle! JAVA8puzzlers
  5. 5. Watching the puzzlers like… #dafaq
  6. 6. Everything works (or doesn't) in the latest Java 8 update
  7. 7. Broken Eggs Tale
  8. 8. What will be the output? A. milk/bread/sausage B. milk/bread/sausage/eggs, don’t forget eggs! C. List<String> list = new ArrayList<>(); list.add("milk"); list.add("bread"); list.add("sausage"); Stream<String> stream = list.stream(); list.add("eggs, don’t forget eggs!"); stream.forEach(System.out::println);
  9. 9. Late binding, duh… List<String> list = new ArrayList<>(); list.add("milk"); list.add("bread"); list.add("sausage"); Stream<String> stream = list.stream(); list.add("eggs, don’t forget eggs!"); stream.forEach(System.out::println);
  10. 10. Late binding, duh… List<String> list = new ArrayList<>(); list.add("milk"); list.add("bread"); list.add("sausage"); Stream<String> stream = list.stream(); list.add("eggs, don’t forget eggs!"); stream.forEach(System.out::println);
  11. 11. Going Vegan
  12. 12. What will be the output? A. milk/bread/sausage B. milk/bread/eggs, don’t forget eggs! C. milk/bread/ConcurrentModificationException D. ConcurrentModificationException List<String> list = new ArrayList<>(); list.add("milk"); list.add("bread"); list.add("sausage"); list = list.subList(0, 2); //No sausage, please! Stream<String> stream = list.stream(); list.add("eggs, don’t forget eggs!"); stream.forEach(System.out::println);
  13. 13. Sometimes it’s just a bug…
  14. 14. Execute ’em all
  15. 15. What’s the difference between 1 and 2? A. 1 compiles, 2 does not B. 2 compiles, 1 does not C. Same same, both work fine D. Same same, both won’t compile public void killAll(){ ExecutorService ex = Executors.newSingleThreadExecutor(); List<String> sentence = Arrays.asList("Punish"); ex.submit(() -> Files.write(Paths.get("Sentence.txt"), sentence) ); // 1 ex.submit(() -> { Files.write(Paths.get("Sentence.txt"), sentence); }); // 2 }
  16. 16. Semicolons are the evil!
  17. 17. What’s the difference between 1 and 2? A. 1 compiles, 2 does not B. 2 compiles, 1 does not C. Same same, both work fine D. Same same, both won’t compile public void killAll(){ ExecutorService ex = Executors.newSingleThreadExecutor(); List<String> sentence = Arrays.asList("Punish"); ex.submit(() -> Files.write(Paths.get("Sentence.txt"), sentence) ); // 1 ex.submit(() -> { Files.write(Paths.get("Sentence.txt"), sentence); }); // 2 }
  18. 18. public void killAll(){ ExecutorService ex = Executors.newSingleThreadExecutor(); List<String> sentence = Arrays.asList("Punish"); ex.submit(() -> Files.write(Paths.get("Sentence.txt"), sentence) ); // 1 ex.submit(() -> { Files.write(Paths.get("Sentence.txt"), sentence); }); // 2 } @FunctionalInterface public interface Runnable { public abstract void run(); } @FunctionalInterface public interface Callable<V> { V call() throws Exception; }
  19. 19. Mad Max
  20. 20. How that will work? A. Compilation error B. Runtime Exception C. 3 D. Something else System.out.println( Stream.of(-3, -2, -1, 0, 1, 2, 3).max(Math::max).get() );
  21. 21. How about now? A. −3 B. −1 C. 0 D. Something else System.out.println( Stream.of(-3, -2, -1, 0, 1, 2, 3).max(Math::max).get() );
  22. 22. How about now? A. −3 B. −1 C. 0 D. Something else System.out.println( Stream.of(-3, -2, -1, 0, 1, 2, 3).max(Math::max).get() );
  23. 23. • Math.max(−3, −2) = −2 < 0  −3 < −2, selecting−2 • Math.max(−2, −1) = −1 < 0  −2 < −1, selecting−1 • Math.max(−1, 0) = 0  −1 == 0, keeping−1 • Math.max(−1, 1) = 1 > 0  −1 > 1, keeping−1 • Math.max(−1, 2) = 2 > 0  −1 > 2, keeping−1 • Math.max(−1, 3) = 3 > 0  −1 > 3, keeping−1 Stream.of(-3, -2, -1, 0, 1, 2, 3).max(Math::max).get()
  24. 24. Let’s upgrade the stack!
  25. 25. What will happen? A.Maps will switch B.Both will become oldSchool C.Both will become hipster D.Really?! That won’t even compile! Map<String, String> oldSchool = initOldSchoolStack(); // oldSchool = {buildTool=maven, lang=java, db=db2} Map<String, String> proper = initHipsterStack(); // proper = {buildTool=npm, lang=javascript, db=elastic} oldSchool.replaceAll(proper::put);
  26. 26. void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) V put(K key, V value); Map interface oldSchool.replaceAll(proper::put);
  27. 27. void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) V put(K key, V value); Map interface final BiFunction<String, String, String> function = (key, value) -> proper.put(key, value); for (Map.Entry<String, String> entry : oldSchool.entrySet()) entry.setValue(function.apply(entry.getKey(), entry.getValue()));
  28. 28. void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) V put(K key, V value); Map interface final BiFunction<String, String, String> function = (key, value) -> proper.put(key, value); for (Map.Entry<String, String> entry : oldSchool.entrySet()) entry.setValue(function.apply(entry.getKey(), entry.getValue()));
  29. 29. How many lines will be the same? List<String> kitties = Arrays.asList("Soft", "Warm", "Purr"); Comparator<String> kittiesComparator= Comparator.nullsLast(Comparator.naturalOrder()); System.out.println(Collections.max(kitties, kittiesComparator)); System.out.println(kitties.stream().collect(Collectors.maxBy(kittiesComparator)).get()); System.out.println(kitties.stream().max(kittiesComparator).get()); A.All lines the same B.Two lines the same C.All different D.Four different
  30. 30. How about now? List<String> kitties = Arrays.asList("Soft", null, "Purr"); Comparator<String> kittiesComparator= Comparator.nullsLast(Comparator.naturalOrder()); System.out.println(Collections.max(kitties, kittiesComparator)); System.out.println(kitties.stream().collect(Collectors.maxBy(kittiesComparator)).get()); System.out.println(kitties.stream().max(kittiesComparator).get()); A.All lines the same B.Two lines the same C.All different D.Four different
  31. 31. How about now? List<String> kitties = Arrays.asList("Soft", null, "Purr"); Comparator<String> kittiesComparator= Comparator.nullsLast(Comparator.naturalOrder()); System.out.println(Collections.max(kitties, kittiesComparator)); System.out.println(kitties.stream().collect(Collectors.maxBy(kittiesComparator)).get()); System.out.println(kitties.stream().max(kittiesComparator).get()); A.All lines the same B.Two lines the same C.All different D.Four different
  32. 32. List<String> kitties = Arrays.asList("Soft", null, "Purr"); Comparator<String> kittiesComparator= Comparator.nullsLast(Comparator.naturalOrder()); System.out.println(Collections.max(kitties, kittiesComparator));
  33. 33. List<String> kitties = Arrays.asList("Soft", null, "Purr"); Comparator<String> kittiesComparator= Comparator.nullsLast(Comparator.naturalOrder()); System.out.println(kitties.stream().collect(Collectors.maxBy(kittiesComparator)).get());
  34. 34. List<String> kitties = Arrays.asList("Soft", null, "Purr"); Comparator<String> kittiesComparator= Comparator.nullsLast(Comparator.naturalOrder()); System.out.println(kitties.stream().max(kittiesComparator).get());
  35. 35. null Caught: java.lang.NoSuchElementException Caught: java.lang.NullPointerException Consistency, yeah.
  36. 36. Mutants
  37. 37. How to cast to a type without declaring it? interface Cat{ default void meow() {System.out.println(”meow ");}} interface Dog{ default void bark() {System.out.println(”woof ");}} public static void main(String[] args) { class Dogcatimplements Dog, Cat{} test(new Dogcat()); } static void test(Object obj) { def x = (?)obj; x.meow (); x.bark (); }
  38. 38. How to cast to a type without declaring it? static void test(Object obj) { // A. Will that work? Dog& Catx = (Dog& Cat) obj; x.meow (); x.bark (); } static void test(Object obj) { // B. Will that work? ((Consumer<? extends Dog& Cat>)(x -> { x.meow (); x.bark (); })).accept((Dog& Cat)obj); } static void test(Object obj) { // C. Will that work? Optional.of((Dog& Cat) obj) .ifPresent(x -> { x.meow (); x.bark (); });} // D. You’re two sick bastards. interface Cat{ default void meow() {System.out.println(”meow");}} interface Dog{ default void bark() {System.out.println(”woof");}} public static void main(String[] args) { class Dogcat implements Dog, Cat{} test(new Dogcat()); }
  39. 39. How to cast to a type without declaring it? static void test(Object obj) { // A. Will that work? Dog & Cat x = (Dog & Cat) obj; x.meow(); x.bark(); } static void test(Object obj) { // B. Will that work? ((Consumer<? extends Dog & Cat>)(x -> { x.meow(); x.bark(); })).accept((Dog & Cat)obj); } static void test(Object obj) { // C. Will that work? Optional.of((Dog & Cat) obj) .ifPresent(x -> { x.meow(); x.bark(); });} // D. You’re two sick bastards. interface Cat{ default void meow() {System.out.println(”meow");}} interface Dog{ default void bark() {System.out.println(”woof");}} public static void main(String[] args) { static class Dogcat implements Dog, Cat{} test(new Dogcat()); }
  40. 40. Bill Gates explains how that works
  41. 41. static void test(Object obj) { // C. Will that work? Optional.of((Dog & Cat) obj) .ifPresent(x -> { x.meow(); x.bark(); });}
  42. 42. Viktor Gamov and Baruch Sadogursky call customer service:
  43. 43. What will be the output? 1. HOTEL ECHO LIMA LIMA OSCAR/ HOTEL ECHO LIMA LIMA OSCAR 2. HELLO / HOTEL ECHO LIMA LIMA OSCAR 3. HOTEL ECHO LIMA LIMA OSCAR/ HELLO 4. HELLO/HELLO public class Test { String str; void run() { str = "hello "; Supplier<String> s1 = str::toUpperCase; Supplier<String> s2 = () -> str.toUpperCase(); str = "Hotel Echo Lima Lima Oscar "; System.out.println(s1.get()); System.out.println(s2.get()); } }
  44. 44. What will be the output? 1. HOTEL ECHO LIMA LIMA OSCAR/ HOTEL ECHO LIMA LIMA OSCAR 2. HELLO / HOTEL ECHO LIMA LIMA OSCAR 3. HOTEL ECHO LIMA LIMA OSCAR/ HELLO 4. HELLO/HELLO public class Test { String str; void run() { str = ”hello"; Supplier<String> s1 = str::toUpperCase; Supplier<String> s2 = () -> str.toUpperCase(); str = ”Hotel Echo Lima Lima Oscar"; System.out.println(s1.get()); System.out.println(s2.get()); } }
  45. 45. What will happen? 1. ConcurrentModificationException 2. ArrayIndexOutOfBoundsException 3. NullPointerException 4. No exceptions, all good List<String> list = new ArrayList<>(Arrays.asList("Arnie", "Chuck", "Slay")); list.stream().forEach(x -> { if(x.equals("Chuck")) { list.remove(x); } });
  46. 46. Java 8 vs Chuck Norris
  47. 47. What will happen? A. ConcurrentModificationException B. ArrayIndexOutOfBoundsException C. NullPointerException D. No exceptions, all good List<String> list = new ArrayList<>(Arrays.asList("Arnie", "Chuck", "Slay")); list.stream().forEach(x -> { if(x.equals("Chuck")) { list.remove(x); } });
  48. 48. Here’s why: stream().forEach()  spliterator().forEachRemaining() forEachRemaining checks for mod count once, in the end Removing element adds null to the end of the array: ["Arne", "Chuck", "Slay"]  ["Arne", "Slay", null] On the last iteration if(null.equals("Chuck")) fails with NPE (didn’t get to CME) Use list.removeIf("Chuck"::equals);
  49. 49. System.out.println(Optional.of("rtfm").orElseGet(null)); System.out.println(Optional.empty().map(null).orElse("rtfm")); What will be the output? A.rtfm / rtfm B.rtfm / NullPointerException C.NullPointerException / NullPointerException D.NullPointerException / rtfm
  50. 50. System.out.println(Optional.of("rtfm").orElseGet(null)); System.out.println(Optional.empty().map(null).orElse("rtfm")); What will be the output? A.rtfm /rtfm B.rtfm / NullPointerException C.NullPointerException / NullPointerException D.NullPointerException / rtfm
  51. 51. Conclusions
  52. 52. - Write readable code! - Comment all the tricks - Sometimes it’s a bug - Static code analysis FTW - intellij IDEA! - Rtfm - Don’t abuse lambdas and streams!
  53. 53. - Trust us, we have much more where those came from. - Puzzlers? Gotchas? Fetal position inducing behavior? - puzzlers jfrog.com
  54. 54. Did you like it? Praise us on twitter and in the feedback form! - java8puzzlers - gamussa - jbaruch Didn’t like it? /dev/null

×