This is keySet() method on HashMap class from JDK. Why did the author assign the field keySet to local variable ks?
If you look at the keySet declaration in the abstract class AbstractMap, you will see that it is defined as:
transient volatile Set keySet;
Since it is volatile, reading it just once by using the local variable assignment is cheaper than reading it twice as would be in the other example you provided.
Furthermore, if you were to return the keySet variable directly, then all the client code would be dealing with a volatile reference vs. a non-volatile reference (i.e. the Set)