Thursday, August 21, 2014

Java 8 Lambdas

First of all - have you ever asked yourself a question - why i need to create a Java Interface with 1 single method?
Hell! Why to create a file if the only thing i want is to create 1 single generic function!
If you did then you are absolutely right! There are many functional languages that spinning around that idiom .

So that's exactly that Java 8 did. They just defined thats kind of Generic interfaces and main of them are :

Interface name Arguments Returns Example
Predicate<T> T boolean Has this album been released yet?
Consumer<T> T void Printing out a value
Function<T,R> T R Get the name from an Artist object
Supplier<T> None T A factory method
UnaryOperator<T> T T Logical not (!)
BinaryOperator<T> (T, T) T Multiplying two numbers (*)

But that's no the end.
In order to provide us an option to write gentle code in already existing classes of the SDK
Stream API had been added

for example on a list you can now convert into stream and the proceed
Example :

long count = allArtists.stream().filter(artist -> artist.isFrom("London")).count();

And this gives us an option writing VERY short and gentle
Now we can create functions on the fly by only writing
()->do something
and pass it to some function

Examples:

Converting Stream to list:
Stream.of("a", "b", "c").collect(Collectors.toList());

Mapping ( transforming a collection)
List<String> collected = Stream.of("a", "b", "hello")
         .map(string -> string.toUpperCase())
         .collect(toList());

Filtering
Stream.of("a", "b", "hello")
.filter(value -> isDigit(value.charAt(0)))
.collect(toList());

flatMap
Is splitting every subelement to stream
Stream.of(asList(1, 2), asList(3, 4))
.flatMap(numbers -> numbers.stream())
.collect(toList());

Max and Min
Track shortestTrack = tracks.stream().min(Comparator.comparing(track -> track.getLength())).get();

Reducing
Stream.of(1, 2, 3)
.reduce(0, (acc, element) -> acc + element);

Combining actions together
album.getMusicians()
.filter(artist -> artist.getName().startsWith("The"))
.map(artist -> artist.getNationality())
.collect(toSet());

Great article to read
http://javarevisited.blogspot.co.il/2014/02/10-example-of-lambda-expressions-in-java8.html

No comments:

Post a Comment