-
Notifications
You must be signed in to change notification settings - Fork 82
/
echo
executable file
·54 lines (46 loc) · 1.47 KB
/
echo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/home/nipa/.sdkman/candidates/java/current/bin/java --source 11
// To run this, update the path in the first line to point to your `java` binary,
// then run `./echo` in your terminal. Nothing much will happen - for the full
// story, run ...
//
// cat echo-haiku.txt | ./echo
//
// ... with one of the command line flags `--sort` or `..reverse`.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
public class Echo {
public static void main(String[] args) throws IOException {
var lines = readInput();
for (var arg : args)
lines = modifyStream(arg, lines);
lines.forEach(System.out::println);
}
private static Stream<String> modifyStream(String arg, Stream<String> input) {
switch (arg){
case "--sort": return input.sorted();
case "--unique": return input.distinct();
case "--reverse": return reverse(input);
default: {
System.out.println("Unknown argument '" + arg + "'.");
return input;
}
}
}
private static Stream<String> reverse(Stream<String> input) {
var reversed = new ArrayList<String>();
input.forEach(line -> reversed.add(0, line));
return reversed.stream();
}
private static Stream<String> readInput() throws IOException {
var reader = new BufferedReader(new InputStreamReader(System.in));
if (!reader.ready())
return Stream.empty();
else
return reader.lines();
}
}