Java Reference
In-Depth Information
(
name
,
nationality
) ->
new
new
Artist
(
name
,
nationality
)
We can also write this using method references:
Artist:
:
new
new
This code is not only shorter but also a lot easier to read.
Artist::new
immediately tells you
that you're creating a new
Artist
without your having to scan the whole line of code.
Another thing to notice here is that method references automatically support multiple para-
meters, as long as you have the right functional interface.
It's also possible to create arrays using this method. Here is how you would create a
String
array:
String
[]::
new
new
We'll be using method references from this point onward where appropriate, so you'll be
seeing a lot more examples very soon. When we were first exploring the Java 8 changes, a
friend of mine said that method references “feel like cheating.” What he meant was that, hav-
ing looked at how we can use lambda expressions to pass code around as if it were data, it
felt like cheating to be able to reference a method directly.
It's OK—it's not cheating! You have to bear in mind that every time you write a lambda ex-
pression that looks like
x -> foo(x)
, it's really doing the same thing as just the method
foo
on its own. All method references do is provide a simpler syntax that takes advantage of this
fact.
Element Ordering
One topic I haven't discussed so far that pertains to collections is how elements are ordered
in streams. You might be familiar with the concept that some types of
Collection
, such as
List
, have a defined order, and collections like
HashSet
don't. The situation with ordering
becomes a little more complex with
Stream
operations.
A
Stream
intuitively presents an order because each element is operated upon, or en-
countered, in turn. We call this the
encounter order
. How the encounter order is defined de-
pends on both the source of the data and the operations performed on the
Stream
.