VOOZH about

URL: https://www.javacodegeeks.com/2015/04/java-8-lambdas-in-one-line.html

⇱ Java 8 Lambdas in One Line - Java Code Geeks


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 Shaya
April 8th, 2015Last Updated: April 8th, 2015
1 90 1 minute read

Daniel Shaya

Daniel has been programming in Java since it was in beta. Working predominantly in the finance industry he has created real time trading and margin risk applications. He is currently a director at OpenHFT where we are building next generation Java low latency products.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
me
11 years ago

If this is the future then we are doomed.

0
Reply
Back to top button
Close
wpDiscuz