21 April 2014

Java8 Stream api throughout the JDK

According to My first look to java8 lambda and streams, I can tell that this new features of Java8 will make our lives much fun and easier..

One thing is that, how many places in JDK I can use the funny stream-api with lambda in?

I have grepped the code (Using eclipse) to find interesting places where we can start using the stream-api.

Result of grep:

java.io.BufferedReader
java.nio.file.Files
java.util.Arrays
java.util.Collections.AsLIFOQueue
java.util.Collections.CheckedCollection
java.util.Collection
java.util.Collections
java.util.Collections.CopiesList
java.util.Collections.SetFromMap
java.util.Collections.SynchronizedCollection
java.util.Collections.UnmodifiableCollection
java.util.Collections.UnmodifiableMap.UnmodifiableEntrySet
java.util.jar.JarFile
java.util.regex.Pattern
java.util.zip.ZipFile

I can find many interesting places like the BufferedReader, Files and of course the Collection API.

I've some fun with the Stream-api with Files and BufferedReader classes ...
See inline comments for explanation


package helloJava8;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

public class LambdaExpr {

    public static void main(String[] args) throws IOException {

        String searchPath = "/bin/";
        String command = "which";

        Optional<Path> commandFound =
        // return the Stream that I gonna walkthrough
        Files.list(Paths.get(searchPath))
        // map the path to the file name, ex from /bin/which to which
                .map(p -> p.getFileName())
                // match the command name to "which"
                .filter(s -> command.equals(s.toString()))
                // find first match and end the stream
                .findFirst();

        // check the optional, BTW, Optional is very interesting API too
        if (commandFound.isPresent()) {
            // regular Java7 code
            BufferedReader reader = new BufferedReader(new FileReader(searchPath + command));
            // here the interesting part, get Stream from the Buffered Reader
            // and here we go.
            reader.lines().forEach(l -> System.out.println(l));
            reader.close();
        }
    }
}



Thanks.

No comments: