Last active
September 12, 2018 23:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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