Java 8 Lambda example

Java Lambdas work about the same as other languages, except they use -> rather than =>.

For instance, you can use these to filter a list with the streams API:

List data = new ArrayList();

data.add("test1");
data.add("test2");
data.add("test3");
data.add("test4");
data.add("test5");

Optional result =
  data.stream().filter(
    (x) -> x.equals("test3")
  ).findFirst();

if (result.isPresent()) {
    System.out.println(result.get());
}

This is one of the few examples of Java code where it can successfully infer the type of the arguments selected.

Leave a Reply

Your email address will not be published. Required fields are marked *