Converting between java.time.LocalDateTime and java.util.Date

Short answer: Date in = new Date(); LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault()); Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant()); Explanation: (based on this question about LocalDate) Despite its name, java.util.Date represents an instant on the time-line, not a “date”. The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start … Read more

Explicitly calling a default method in Java

As per this article you access default method in interface A using A.super.foo(); This could be used as follows (assuming interfaces A and C both have default methods foo()) public class ChildClass implements A, C { @Override public void foo() { //you could completely override the default implementations doSomethingElse(); //or manage conflicts between the same … Read more

How to serialize a lambda?

Java 8 introduces the possibility to cast an object to an intersection of types by adding multiple bounds. In the case of serialization, it is therefore possible to write: Runnable r = (Runnable & Serializable)() -> System.out.println(“Serializable!”); And the lambda automagically becomes serializable.

javafx 8 compatibility issues – FXML static fields

It sounds like you are trying to inject a TextField into a static field. Something like @FXML private static TextField myTextField ; This apparently worked in JavaFX 2.2. It doesn’t work in JavaFX 8. Since no official documentation ever supported this use, it’s doesn’t really violate backward compatibility, though in fairness the documentation on exactly … Read more

Convert Iterable to Stream using Java 8 JDK

There’s a much better answer than using spliteratorUnknownSize directly, which is both easier and gets a better result. Iterable has a spliterator() method, so you should just use that to get your spliterator. In the worst case, it’s the same code (the default implementation uses spliteratorUnknownSize), but in the more common case, where your Iterable … Read more

Is method reference caching a good idea in Java 8?

You have to make a distinction between frequent executions of the same call-site, for stateless lambda or stateful lambdas, and frequent uses of a method-reference to the same method (by different call-sites). Look at the following examples: Runnable r1=null; for(int i=0; i<2; i++) { Runnable r2=System::gc; if(r1==null) r1=r2; else System.out.println(r1==r2? “shared”: “unshared”); } Here, the … Read more

What does the arrow operator, ‘->’, do in Java?

That’s part of the syntax of the new lambda expressions, to be introduced in Java 8. There are a couple of online tutorials to get the hang of it, here’s a link to one. Basically, the -> separates the parameters (left-side) from the implementation (right side). The general syntax for using lambda expressions is (Parameters) … Read more