• Register
100 points
2

In this article, I will explain about Java 8 collections and that developers should know.

  • Lambda expressions

  • Collections

  • Method Expressions

  • Streams 

  • Optional

 

 

Lambda Expression

(int a) -> a * 2; // Calculate the double of a
a -> a * 2; // or simply without type
(a, b) -> a + b; // Sum of 2 parameters

If the lambda is more than one expression we can use { } and return

(x, y) -> {
    int sum = x + y;
    int avg = sum / 2;
    return avg;
}

A lambda expression cannot stand alone in Java, it needs to be associated with a functional interface.

interface MyMath {
    int getDoubleOf(int a);
}

MyMath d = a -> a * 2; // associated to the interface
d.getDoubleOf(4); // is 8

 

Note on interface limitations

interface Pair<A, B> {
    A first();
    B second();
}

 

A steam of type Stream<Pair<String, Long>> :

  • stream.sorted(Comparator.comparing(Pair::first)) // ok
  • stream.sorted(Comparator.comparing(Pair::first).thenComparing(Pair::second)) // dont work

Java cannot infer type for the .comparing(Pair::first) part and fallback to Object, on which Pair::first cannot be applied.

 

Read More ...

100 points
2