Created
May 9, 2015 12:32
-
-
Save ClausPolanka/d379a32efef65c827cee to your computer and use it in GitHub Desktop.
FlowDesign EBC impl via Java 8
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 stringcalculator; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
public class StringCalculator { | |
public static final String SEPARATORS = "(,|\\n)"; | |
public List<Consumer<Integer>> onResult = new ArrayList<>(); | |
public void add(String numbers) { | |
validate(numbers, | |
this::sum, | |
(Void) -> { throw new IllegalArgumentException(); }); | |
} | |
private void validate( | |
String numbers, | |
Function<String, Integer> onSuccess, | |
Consumer<Void> onError) { | |
if (numbers.length() > 0) { | |
onResult.stream().forEach(c -> c.accept(onSuccess.apply(numbers))); | |
} else onError.accept(null); | |
} | |
private int sum(String numbers) { | |
return Arrays.asList(numbers.split(SEPARATORS)) | |
.stream() | |
.map(Integer::parseInt) | |
.mapToInt(Integer::intValue) | |
.sum(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment