If you ask my opinion about the most interesting feature added to a static type languages like Java, I would answer it is definitely 'Lambda'.
Lambda expressions reduces lines of code while increasing the readability and expressiveness of the code. My friends know me as a huge fan of lambda expressions for years. I've always enjoy to code using lambda calculus.
Here, I want to show some magic you can do with lambda every day! I want to compare some lambda-less and lambda solutions:
Consider this array which contains some cars with their relative mileages:
List<Car> cars = Arrays.asList( new Car("Mercedes", "Germany", 2500), new Car("BMW", "Germany", 2500), new Car("Porsche", "Germany", 2500), new Car("Ford", "USA", 2500), new Car("Toyota", "Japan", 2500), new Car("Ferrari", "Italy", 2500) );
Scenario 1. A list of German cars
The lambda-less solution is:
List<Car> germanCars = new ArrayList<Car>(); for (int i=0 ; i<cars.size() ; i++) { Car car = cars.get(i); if (car.getCountry() == "Germany") germanCars.add(car); }
And the solution with lambda:
List<Car> germanCars = cars.stream() .filter(car -> car.getCountry() == "Germany") .collect(Collectors.toList());
Scenario 2. A list of Old car names
The lambda-less solution is:
List<String> namesOfOldCars = new ArrayList<String>(); for(int i=0 ; i<cars ; i++) { Car car = cars.get(i); if (car -> car.milage > 10000) namesOfOldCars.add(car.getName());
And the solution with lambda:
List<String> namesOfOldCars = cars.stream() .filter(car -> car.milage > 10000) .map(car -> car.name) .collect(Collectors.toList());
Believe me, after learning how to use Lambda, it's really hard to write code without it, even if you're writing just some samples for your blog (me, now!). So, accept my apologize if I'm not going to write more lambda-less equivalent codes. Just try to guess what the lambda-less code would be!
Some more fun with Lambda
boolean isThereAnyOldGermanCar = cars.stream() .anyMatch( car -> car.getCountry() == "Germany" && car.getMilage() > 10000 ); boolean doesAllCountryNamesContainA = cars.stream() .allMatch(car -> car.getCountry().toUpperCase().contains("A")); List<Car> listOf2CarsSkippingFirstCar = cars.stream() .skip(1) .limit(2) .collect(Collectors.toList());
If you are more interested
In the case that I was successful to make you interested about Lambda(!), you can find more fun in the following links:
A good quick start from Oracle
Reference API for Stream
An article about Functional Programming in Java
Java 8 Tutorial: Lambda Expressions, Streams, and More
It's `Collectors.toList()t`, not `Collections.toList()`.
@Ali Dehghani Thank you. I've just corrected it.