patternjavaMinor
Sending duplicate to heaven with Java 8
Viewed 0 times
heavenwithduplicatesendingjava
Problem
Follow up to Duplicate like a weapon, arrays like heaven.
@rolfl suggested in chat that I try to complete this challenge again in a Java 8 friendly way. I took the opportunity to also employ the algorithm suggested in this brilliant answer.
I'm not familiar with Java 8 features, but am definitely interested in using it more and finding the best ways to implement it.
This ended up shorter than I expected. Is this best? I was thinking of doing it my way as well, but the
@rolfl suggested in chat that I try to complete this challenge again in a Java 8 friendly way. I took the opportunity to also employ the algorithm suggested in this brilliant answer.
I'm not familiar with Java 8 features, but am definitely interested in using it more and finding the best ways to implement it.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
public class ArrayAbsurdityJava8 {
public static void main(String[] args) throws IOException {
Files.lines(new File(args[0]).toPath())
.filter(s -> !s.isEmpty())
.forEach(ArrayAbsurdityJava8::printDuplicate);
}
private static void printDuplicate(String line) {
int length = Integer.parseInt(line.split(";")[0]);
int total = Arrays.stream(line.split(";")[1].split(","))
.mapToInt(Integer::parseInt)
.sum();
System.out.println(total - (length - 1) * (length - 2) / 2);
}
}This ended up shorter than I expected. Is this best? I was thinking of doing it my way as well, but the
boolean comparison requires a for loop (am I wrong?).Solution
line.split(";") is being called twice, so you can assign it to a variable to remove one of the calls.Since we know there's only one
; per line, we can use indexOf to find it, and substring to extract the relevant parts of the string. This may be a little bit faster than calling split(";").Context
StackExchange Code Review Q#80118, answer score: 6
Revisions (0)
No revisions yet.