James Bay
James Bay

Reputation: 29

How to create an analogue of a bash "pipe" command in Java

I'm puzzling over an idea of creating a universal "pipe" method in java for my console Command Line(Bash) application so basically a command like " ls -lt | head" can be executed.

I can't wrap my head around implementing let's say a static method that would take varargs of methods ...given the above bash command, it should be as shown in the snippet below.

my idea is to encapsulate methods within Command objects.

public static void pipe (Command ... commands) {

command1.execute();
command2.execute();
}

Any help would be highly appreciated.

Upvotes: 2

Views: 128

Answers (1)

Liviu Stirb
Liviu Stirb

Reputation: 6075

Assume each command takes the same inputs and returns the same thing. If this is not the case you can take an object as input and return an object and each Command will cast. A basic implementation:

public static <T> T pipe(T input, Command<T>... commands) {

    for (Command<T> com : commands) {
        input = com.execute(input);
    }
    return input;
}

public interface Command<T> {
    T execute(T input);
}

This can be also extended to work with lists of a type, so head command will always store and return first input it got (or first 10).

Anyways I wouldn't do my own implementation. You should look at java 8 stream. A pipeline/stream is a sequence of aggregate operations.

For you question the answer would be like:

    List<Path> lsFirst = Files.list(Paths.get("/")).limit(10).collect(Collectors.<Path>toList());
    System.out.println(lsFirst);

Upvotes: 3

Related Questions