Core Java

Java 8 Lambdas in One Line

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.

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
Notify of
guest

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
me
me
8 years ago

If this is the future then we are doomed.

Back to top button