If you understand this line, or better still can write this code you can pretty much say that you have understood the essence of Java 8 Lambdas. Certainly in as much as they can be used with collections.
I found this in a recent presentation by Peter Lawrey. (Definitely worth watching the whole presentation when you have a spare hour.)
Anyway the task was to find the 20 most frequent words in a file:
As you can see, with Java 8 this can actually be done in a single (albeit rather long) line.
If youβre not used to lambdas the code might seem a little scary but actually itβs pretty declarative and when you get past the logic reads fairly easily.
package util;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Lambdas in one line
*/
public class LambdaTest {
public static List<String> parse(Path path) throws Exception{
return Files.lines(path)
.parallel()
.flatMap(line -> Arrays.asList(line.split("\\b")).stream())
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry<String, Long>::getValue).reversed())
.limit(20)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
public static void main(String... args) throws Exception{
System.out.println(parse(Paths.get(args[0])));
}
}
| Reference: | Java 8 Lambdas in One Line from our JCG partner Daniel Shaya at the Rational Java blog. |
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Thank you!
We will contact you soon.
π Photo of Daniel Shaya
Daniel ShayaApril 8th, 2015Last Updated: April 8th, 2015
Daniel ShayaApril 8th, 2015Last Updated: April 8th, 2015
1 90 1 minute read

This site uses Akismet to reduce spam. Learn how your comment data is processed.
If this is the future then we are doomed.