From charlesreid1

Revision as of 22:38, 5 July 2017 by Admin (talk | contribs) (Created page with "==Lambda Expressions== When it comes to dealing with functions as first-class objects in the language, Java is much more limited than Python. In fact, it was not until Java 8...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Lambda Expressions

When it comes to dealing with functions as first-class objects in the language, Java is much more limited than Python. In fact, it was not until Java 8 that Java finally got lambda expressions, which are ways of defining functions using in-place, shorthand expressions.

Lambdas for Comparators

You can throw together a fast comparator with a single lambda function, by skipping the class definition and the compare method, and simply using a lambda function instead.

Suppose I have a simple Point object storing two elements:

public class Point {
    public int x, y;
    public Point(int x0, int y0) { this.x = x0; this.y = y0; }
    public String tString() { return "("+this.x+","+this.y+")";}
}

Now suppose we want to sort point objects by their x coordinates only (ignoring y coordinates). We start by defining a Comparator object that wraps Point objects: Comparator<Point> pc.


Comparator<Developer> byName = (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());



References

Oracle Java tutorial on lambda expressions: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html