Skip to content

Instantly share code, notes, and snippets.

@topriddy
Last active September 12, 2018 23:55
Show Gist options
  • Save topriddy/e49d696833c739d13b34a10e2f482173 to your computer and use it in GitHub Desktop.
Save topriddy/e49d696833c739d13b34a10e2f482173 to your computer and use it in GitHub Desktop.
devslack's sum-files-challenge Java solution (Draft till when I can make it better to submit issue). Runs average of 6secs after warm up. https://github.com/devcenter-square/sum-files-challenge
package com.topriddy.devslack;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.function.Function.identity;
public class ProgramSolution {
private final static String pathName = "/Users/topriddy/dev/sum-files-challenge-data/files";
public static void main(String args[]) throws Exception {
sumFiles(pathName);
sumFiles(pathName);
sumFiles(pathName);
}
static void sumFiles(String dataPath) throws Exception {
System.out.println("Starting...");
Long startTime = System.currentTimeMillis();
List<Path> files = Files.walk(Paths.get(dataPath))
.filter(p -> !Files.isDirectory(p))
.collect(Collectors.toList());
Long sum = files.parallelStream()
.map(path -> {
try {
return Files.lines(path);
} catch (IOException ioex) {
ioex.printStackTrace();
return Stream.empty();
}
})
.map(lines -> lines.map(line -> asList(((String) line).split(",")).stream())
.flatMap(identity())
.map(value -> Long.valueOf(value))
)
.flatMap(identity())
.mapToLong(v -> v).sum();
Long endTime = System.currentTimeMillis();
System.out.println("Sum of numbers in file is : " + sum);
System.out.printf("\nDuration: %f seconds", (endTime - startTime) / 1000.0);
System.out.println("\nEnd");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment