Skip to content

Instantly share code, notes, and snippets.

@yole
Last active September 15, 2016 19:21
Show Gist options
  • Save yole/50c3b1fc28681b7b339b to your computer and use it in GitHub Desktop.
Save yole/50c3b1fc28681b7b339b to your computer and use it in GitHub Desktop.
package chapter01;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Stream;
public class LineCount {
private final int total;
private final int empty;
public LineCount(int total, int empty) {
this.total = total;
this.empty = empty;
}
private static LineCount countLines(Path path) throws IOException {
if (Files.isDirectory(path)) return null;
List<String> lines = Files.readAllLines(path);
Stream<String> emptyLines = lines.stream().filter(
(String line) -> line.trim().isEmpty());
return new LineCount(lines.size(), (int) emptyLines.count());
}
public static void main(String[] args) {
try {
for (String arg : args) {
LineCount lineCount = countLines(Paths.get(arg));
if (lineCount == null) continue;
System.out.println(arg + ": " + lineCount.total +
" total lines, " + lineCount.empty + " empty lines");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package chapter01.linecount
import java.io.File
data class LineCount(val total: Int,
val empty: Int)
fun File.countLines(): LineCount? {
if (isDirectory()) return null
val lines = readLines()
val emptyLines = lines.filter { it.trim().isEmpty() }
return LineCount(lines.size(), emptyLines.size())
}
fun main(args: Array<String>) {
for (fileName in args) {
val (total, empty) = File(fileName).countLines() ?: continue
println("$fileName: $total total lines, $empty empty lines")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment