JavaOne – Modern Java Recipes

Main menu:

Topics

Recent Posts

Feeds

RSS Feed RSS - Posts

October 2017
M T W T F S S
« Sep    
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Past Posts

Java/Java EE

JDBC

Other

JavaOne – Modern Java Recipes

October 5th, 2017 by Jeanne Boyarsky

“Modern Java Recipes”

Speaker: Ken Kousen

For more blog posts from JavaOne, see the table of contents


All examples in this talk are in:
https://github.com/kousen/java_8_recipes

Lazy Streams

  • Streams – doesn’t store elements, doesn’t modify source, lazy when possible, destructive (can only run once)
  • Showed how findFirst() doesn’t cause all intermediate operations to run against all data in stream
  • findFirst() is a short circuiting terminal operation
  • Not many short circuiting stream operations. limit() is one as well for intermediate operation

Debugging streams

  • Eclipse and IntelliJ let you put breakpoints in stream
  • IntelliJ has plugin to see values in stream as go by
  • peek() method
  • Tip: Use a debug log library with peek so easy to turn off

Strings as Streams

  • String does not implement Iterable
  • Arrays.stream() doesn’t work for char[]
  • str.codePoints() returns int stream
  • StringBilder::appendCodePoint gets it back into stringish form
  • Obscure case; source: stack overflow

allMatch, anyMatch, noneMatch

  • all short circuiting terminal operations
  • showed with prime number checker – noneMatch returns as soon as finds example that proves number isn’t prime
  • also showed the assertFalse and anyMatch. I didn’t understand why this wasn’t assertTrue and noneMatch in the book

collect

  • showed three arg version – Supplier, BiConsumer to add single element to the result and anoher BiConsumer ot combine two interim results
  • the combiner isn’t mentioned in the JavaDoc pseudocoe
  • the combiner also gets used for parallel streams
  • reduce() is similar

Reduction

  • count() == mapToLong(e -> 1L).sum()
  • Added a few methods like Integer.sum(a,b) so can use as a BinaryOperator
  • The two argument version of reduce takes an identity for the binary operator. This lets it return a value instead of an Optional
  • Use reduce that takes BiFunction if reducing into a different type

Transforming streams

  • map – one to one mapping
  • flatMap – function from T to a stream. It is one to many where many is a stream
  • Optional also has a flatMap() which is for flattening Optional<Optional<T>> to Optional<T>

Deferred execution

  • Showed logger and how doesn’t build complex string if not needed to log
  • Overload methods to take supplier for this case. Caller just needs to add () ->
  • Don’t worry about this if you string is just a constant
  • Optional.orElseGet works the same way

Partioning and Grouping

  • downstream collectors – use when don’t want list back

Words

  • showed the /user/share/dict/words example
  • need to use try with resources when use Files.lines
  • Comparator.comparingInt(..).reversed().thenComparing(..)

Finally, showed demo of Anartica time zone map. The South pole follows New Zealand time. Which eans has daylight savings time despite getting 6 months of light vs 6 mnonths of dark

My take: Everything in this talk is from the book which I’ve already heard. But I’ve never seen Ken speak and wanted to. And it’s fun seeing things presented out loud. His umor while writing and out loud are similar which is good. I learned a few things in the comments like the IntelliJ debugging plugin.

JavaOne – How to Make a Project Java 9 Compatible

October 5th, 2017 by Jeanne Boyarsky

“How to Make a Project Java 9 Compatible”

Speaker: Nikhil Nanivadekar

For more blog posts from JavaOne, see the table of contents


Examples use Eclipse Collections

Examples from:
https://github.com/nikhilnanivadekar/Java9Compatibility
https://github.com/nikhilnanivadekar/Java9Modules

Reflection

  • Used ArrayListAdapter which uses reflection
  • Got illegal-access warning (when default was warn; now it is permit
  • If run with illegal-access=deny, it fails
  • Lesson: have lots of regression tests so know about such errors
  • Lesson: Allow a lot of time to migrate. Don’t start Friday evening. Long sequence of “just one more compilation error to fix”

Infering types

  • Compler error because can’t assume generictype to return
  • Comes up when class doesn’t have a generic type and try to store it in one that does.
  • Compiler not supposed to infer type
  • Fix is to cast or store in a local variable
  • Similarly need to declare types on class instatiation if not diamond operator usage

NullPointerException

  • collect() now calls Objects.requireNotNull(combiner).
  • In Java 8, a null combiner worked in serial mode because not used.

“I love compiler errors vs runtime exceptions”

Migrating a Java 8 Maven project to Java 9

  • Migrated a maze solving project. Was written recently so not legacy code
  • Switch source/target of maven-compiler-plugin to “9”.
  • Changed JDK in IntelliJ.
  • Maven itself works fine with Java 9. Compiling works. JavaDoc and Enforcer plugins work fine with milestone version; not yet for released versions. Seewiki on support for Java 9 in Maven plugins
  • Looking at modularizing library in future
  • Runs without adding module info file or doing anything else
  • Once add module file, more enforcement happens. ex: error on unnamed packages
  • Eclipse and IntelliJ have quick tip to add requires
  • Important: start with base module
  • If not using a build tool, need to ensure no cyclic dependencies. (build tool takes care of this for you)
  • Add exports clause for module. The compiler error just says the class isn’t found. It doesn’t say it is because the export is missing.
  • Move code in split package to another package updating all callers
  • Delete empty package; can’t have empty package
  • Hide internal packages by not exporting sub-packages

My take: Nice to see issues by example. And nice to see that it wasn’t “all about Jigsaw.” It was a good mix of problem types!

JavaOne – Optional – the mother of all bikesheds

October 5th, 2017 by Jeanne Boyarsky

“Optional – the mother of all bikesheds”

Speaker: Stuart Marks
#OptionalBikeshed

The deck is available online

For more blog posts from JavaOne, see the table of contents


Showed early version of “optional” (stream returning null)

Review of basics

  • Two states – present (contains non null reference) or absent
  • Don’t say “null optional”. Say “absent” or “empty”
  • Optionals are immutable
  • equals() and hashCode() work as one would expect – useful for JUnit because can call assertEquals()

New in Java 9

  • stream() – stream with 0 or 1 elements
  • ifPresentOrElse(Consumer)
  • or(Supplier)

Good code and Best practices

  • Never set an Optional variable to null. It should be Optional.empty() as default.
  • If method returns Optional, never return a null either.
  • Intended for return types where might or might not have a value to return.
  • Don’t call get() as could be empty optional
  • Use isPresent() and get() as last resort
  • Using .map().orElse() chained after stream pipeline gives fluent API calls
  • Calling filter() returns original value only if non-empty optional that matches. else returns empty. Using filter() and orElseThrow() is good for validation
  • [and more see the deck]

My take: Amazed there is so much to say about Optional! Excellent set of best practices. And excellent point on not calling an optional “null.” I needed to leave early as my session is immediately after this one. And I really wanted to know “what’s with the bikeshed” which is covered last.  It’s a nice collection of quotes. So I found the deck and best practices online. There’s also a youtube video linked so you can watch at home.