diff --git a/problems/pom.xml b/problems/pom.xml index a8a2ef9..ee612ef 100644 --- a/problems/pom.xml +++ b/problems/pom.xml @@ -16,14 +16,7 @@ Euler and Latency solutions/tests - - - - io.vavr - vavr - ${vavr.version} - - + org.openjdk.jmh diff --git a/problems/src/main/java/info/jab/fp/euler/EulerProblem09.java b/problems/src/main/java/info/jab/fp/euler/EulerProblem09.java index d0b9e0a..17a74bb 100644 --- a/problems/src/main/java/info/jab/fp/euler/EulerProblem09.java +++ b/problems/src/main/java/info/jab/fp/euler/EulerProblem09.java @@ -1,10 +1,6 @@ package info.jab.fp.euler; -import io.vavr.Tuple; -import io.vavr.Tuple3; -import io.vavr.collection.List; import java.util.stream.LongStream; -import org.apache.commons.lang3.NotImplementedException; /** * Problem 9: Special Pythagorean triplet @@ -20,29 +16,15 @@ */ public class EulerProblem09 { - public Long JavaSolution(long limit) { - - throw new NotImplementedException("¯\\_(ツ)_/¯"); - } - public long JavaStreamSolution(long limit) { + record Tuple3(Long param1, Long param2, Long param3) {} + return LongStream.iterate(1, i -> i + 1) - .mapToObj(i -> new Tuple3<>(i, i, i)) - .filter(t3 -> t3._1 + t3._2 + t3._3 == limit) + .mapToObj(i -> new Tuple3(i, i, i)) + .filter(t3 -> t3.param1() + t3.param2() + t3.param3() == limit) .peek(System.out::println) .limit(1) .count(); } - - public int VAVRSolution(long sum) { - - return List.rangeClosed(1, (int) sum) - .crossProduct() - .filter(t -> t._1 + t._2 < (int) sum) - .map(t -> Tuple.of(t._1, t._2, (int) sum - t._1 - t._2)) - .filter(t -> t._1 * t._1 + t._2 * t._2 == t._3 * t._3) - .map(t -> t._1 * t._2 * t._3) - .head(); - } } diff --git a/problems/src/main/java/info/jab/fp/euler/EulerProblem14.java b/problems/src/main/java/info/jab/fp/euler/EulerProblem14.java index d1f61af..3f5e72d 100644 --- a/problems/src/main/java/info/jab/fp/euler/EulerProblem14.java +++ b/problems/src/main/java/info/jab/fp/euler/EulerProblem14.java @@ -1,7 +1,5 @@ package info.jab.fp.euler; -import io.vavr.Function1; -import io.vavr.collection.Stream; import java.util.stream.LongStream; public class EulerProblem14 { @@ -21,25 +19,4 @@ public long javaStreamSolution(long limit) { .count(); } - public long VAVRSsolution(long limit) { - return Stream.from(limit) - .take((int) limit) - .maxBy(collatzSequenceLength) - .get(); - } - - private final static Function1 collatzRecursive = n -> { - if (n == 1) { - return 1L; - } else { - if (n % 2 == 0) { - return EulerProblem14.collatzRecursive.apply(n / 2) + 1; - } else { - return EulerProblem14.collatzRecursive.apply(3 * n + 1) + 1; - } - } - }; - - private final static Function1 collatzSequenceLength = collatzRecursive.memoized(); - } diff --git a/problems/src/main/java/info/jab/fp/euler/EulerProblem16.java b/problems/src/main/java/info/jab/fp/euler/EulerProblem16.java index 167e378..c55bf2a 100644 --- a/problems/src/main/java/info/jab/fp/euler/EulerProblem16.java +++ b/problems/src/main/java/info/jab/fp/euler/EulerProblem16.java @@ -1,6 +1,5 @@ package info.jab.fp.euler; -import io.vavr.collection.CharSeq; import java.math.BigInteger; /** @@ -19,12 +18,4 @@ public long javaStreamSolution(long power) { .mapToLong(s -> Long.valueOf(s)) .sum(); } - - public long VAVRSolution(long power) { - - return CharSeq.of(BigInteger.valueOf(2).pow((int) power).toString()) - .map(c -> String.valueOf((char) c)) - .map(s -> Long.valueOf(s)) - .fold(0L, (a, b) -> a + b); - } } diff --git a/problems/src/main/java/info/jab/fp/euler/EulerProblem21.java b/problems/src/main/java/info/jab/fp/euler/EulerProblem21.java index c3bc9ec..aa10803 100644 --- a/problems/src/main/java/info/jab/fp/euler/EulerProblem21.java +++ b/problems/src/main/java/info/jab/fp/euler/EulerProblem21.java @@ -1,10 +1,7 @@ package info.jab.fp.euler; -import io.vavr.Function1; -import io.vavr.Tuple; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.LongStream; @@ -64,20 +61,4 @@ public long javaStreamSolution(long limit) { .peek(System.out::println) .sum(); } - - int sumOfDivisors(int n) { - return 1 + io.vavr.collection.Stream.rangeClosed(2, (int) Math.sqrt(n)) - .map(d -> Tuple.of(d, n / d)) - .filter(t -> t._1 * t._2 == n && !Objects.equals(t._1, t._2)) - .map(t -> t._1 + t._2) - .foldLeft(0, (sum, x) -> sum + x); - } - - public int VAVRSolution(int n) { - final Function1 mSumOfDivisors = Function1.of(this::sumOfDivisors).memoized(); - return io.vavr.collection.Stream.range(1, n) - .filter(x -> mSumOfDivisors.apply(mSumOfDivisors.apply(x)).intValue() == x && mSumOfDivisors.apply(x) > x) - //.peek(System.out::println) - .foldLeft(0, (sum, x) -> sum + x + mSumOfDivisors.apply(x)); - } } diff --git a/problems/src/main/java/info/jab/fp/euler/EulerProblem22.java b/problems/src/main/java/info/jab/fp/euler/EulerProblem22.java index b4fe745..6daf6fc 100644 --- a/problems/src/main/java/info/jab/fp/euler/EulerProblem22.java +++ b/problems/src/main/java/info/jab/fp/euler/EulerProblem22.java @@ -1,22 +1,15 @@ package info.jab.fp.euler; - -import io.vavr.Tuple2; -import io.vavr.collection.CharSeq; -import io.vavr.collection.Iterator; -import io.vavr.collection.Stream; -import io.vavr.control.Try; -import java.io.File; -import java.io.FileNotFoundException; -import java.net.URL; +import java.io.IOException; +import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collections; import java.util.List; -import java.util.Scanner; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.regex.Pattern; +import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; @@ -43,19 +36,34 @@ public class EulerProblem22 { .map(l -> l.replaceAll("\"", "")) .collect(toList()); + Function> load = fileName -> { + try { + return Files.lines(Paths.get( + getClass().getClassLoader().getResource(fileName).toURI())) + .collect(Collectors.toList()); + } catch (IOException | URISyntaxException | NullPointerException ex) { + System.out.println(ex.getLocalizedMessage()); + return Collections.emptyList(); + } + }; + + /* Function> load = fileName -> Try.of(() -> Files.lines(Paths.get( getClass().getClassLoader().getResource(fileName).toURI())) .collect(toList())) .onFailure(System.out::println) .getOrElse(Collections.emptyList()); + */ + + record Tuple2(Integer param1, String param2) {} Function, List> addIndex = list -> { AtomicInteger index = new AtomicInteger(0); - return Stream.of(list) + return list.stream() .map(s -> new Tuple2(index.incrementAndGet(), String.valueOf(s))) - .toJavaList(); + .toList(); }; Function> loadFile = fileName -> this.load.andThen(this.split).apply(fileName); @@ -71,7 +79,9 @@ public class EulerProblem22 { Function, Long> sum = list -> list.stream() .map(item -> { - return toDigits.andThen(sumDigits).apply(String.valueOf(item._2)) * Long.valueOf(String.valueOf(item._1)); + return toDigits + .andThen(sumDigits) + .apply(String.valueOf(item.param2())) * Long.valueOf(String.valueOf(item.param1())); }) .reduce(0L, Long::sum); @@ -83,52 +93,4 @@ public long javaStreamSolution() { .apply("euler/p022_names.txt"); } - public long VAVRSolution() { - return readLines(file("euler/p022_names.txt")) - .map(l -> l.replaceAll("\"", "")) - .flatMap(l -> Stream.of(l.split(","))) - .sorted() - .zipWithIndex() - .map(t -> nameScore(t._1, t._2 + 1)) - .sum().longValue(); - } - - long nameScore(String name, long position) { - return CharSeq.of(name) - .map(c -> c - 'A' + 1) - .sum().longValue() * position; - } - - private Stream readLines(File file) { - try { - return Stream.ofAll(new Iterator() { - - final Scanner scanner = new Scanner(file); - - @Override - public boolean hasNext() { - final boolean hasNext = scanner.hasNextLine(); - if (!hasNext) { - scanner.close(); - } - return hasNext; - } - - @Override - public String next() { - return scanner.nextLine(); - } - }); - } catch (FileNotFoundException e) { - return Stream.empty(); - } - } - - private File file(String fileName) { - final URL resource = getClass().getClassLoader().getResource(fileName); - if (resource == null) { - throw new RuntimeException("resource not found"); - } - return new File(resource.getFile()); - } } diff --git a/problems/src/main/java/info/jab/fp/euler/EulerProblem29.java b/problems/src/main/java/info/jab/fp/euler/EulerProblem29.java index b8e0aee..c7eb8ca 100644 --- a/problems/src/main/java/info/jab/fp/euler/EulerProblem29.java +++ b/problems/src/main/java/info/jab/fp/euler/EulerProblem29.java @@ -43,13 +43,4 @@ public long javaStreamSolution(long limit) { return generateSerie.apply(limit).count(); } - public long VAVRSolution(long limit) { - - return io.vavr.collection.Stream.rangeClosed(2, limit) - .map(BigInteger::valueOf) - .flatMap(a -> io.vavr.collection.Stream.rangeClosed(2, (int) limit).map(a::pow)) - .distinct() - .length(); - } - } diff --git a/problems/src/main/java/info/jab/fp/euler/EulerProblem30.java b/problems/src/main/java/info/jab/fp/euler/EulerProblem30.java index 43ddbb8..d872e46 100644 --- a/problems/src/main/java/info/jab/fp/euler/EulerProblem30.java +++ b/problems/src/main/java/info/jab/fp/euler/EulerProblem30.java @@ -1,8 +1,5 @@ package info.jab.fp.euler; -import io.vavr.Tuple; -import io.vavr.collection.CharSeq; -import io.vavr.collection.Stream; import java.util.List; import java.util.function.BiPredicate; import java.util.function.Function; @@ -53,24 +50,4 @@ public long javaStreamSolution(long limit) { .reduce(0l, (l1, l2) -> l1 + l2); } - public long VAVRSolution(long powers) { - return io.vavr.collection.List.rangeClosed(10, maximalSumForPowers(powers)) - .filter(i -> sumOfPowersOfDigits(powers, i) == i) - .sum().longValue(); - } - - private long maximalSumForPowers(long powers) { - return Stream.from(1) - .map(i -> Tuple.of((long) Math.pow(10, i) - 1, io.vavr.collection.List.fill(i, () -> Math.pow(9, powers)).sum().longValue())) - .find(t -> t._1 > t._2) - .map(t -> t._1).get(); - } - - private long sumOfPowersOfDigits(long powers, long num) { - return CharSeq.of(Long.toString(num)) - .map(c -> Character.digit(c, 10)) - .map(d -> (long) Math.pow(d, powers)) - .sum().longValue(); - } - } diff --git a/problems/src/main/java/info/jab/fp/euler/EulerProblem34.java b/problems/src/main/java/info/jab/fp/euler/EulerProblem34.java index ed17695..74a66bf 100644 --- a/problems/src/main/java/info/jab/fp/euler/EulerProblem34.java +++ b/problems/src/main/java/info/jab/fp/euler/EulerProblem34.java @@ -1,8 +1,5 @@ package info.jab.fp.euler; -import io.vavr.Function1; -import io.vavr.collection.CharSeq; -import io.vavr.collection.Stream; import java.math.BigInteger; import java.util.List; import java.util.function.Function; @@ -40,23 +37,4 @@ public long javaStreamSolution() { .reduce(0L, (l1, l2) -> l1 + l2); } - public int VAVRSolution() { - return Stream.rangeClosed(3, 2_540_160) // 9! * 7 = 2 540 160 is a seven digit number, as is 9! * 8, therefor 9! * 7 is the definitive upper limit we have to investigate. - .filter(i -> i == sumOfDigitFactorial(i)) - .peek(System.out::println) - .sum().intValue(); - } - - private int sumOfDigitFactorial(int num) { - return CharSeq.of(Integer.toString(num)) - .map(c -> Character.digit(c, 10)) - .map(MEMOIZED_FACTORIAL) - .sum().intValue(); - } - - final Function1 MEMOIZED_FACTORIAL = Function1.of(this::factorial).memoized(); - - BigInteger factorial(int n) { - return Stream.rangeClosed(1, n).map(BigInteger::valueOf).fold(BigInteger.ONE, BigInteger::multiply); - } } diff --git a/problems/src/main/java/info/jab/fp/latency/LatencyProblem01.java b/problems/src/main/java/info/jab/fp/latency/LatencyProblem01.java index 4bf8bfd..f2c7e60 100644 --- a/problems/src/main/java/info/jab/fp/latency/LatencyProblem01.java +++ b/problems/src/main/java/info/jab/fp/latency/LatencyProblem01.java @@ -4,9 +4,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import info.jab.fp.euler.IEulerType3; -import io.vavr.control.Try; import java.math.BigInteger; +import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -57,20 +57,32 @@ public BigInteger JavaSolution() { return null; } + /* Function toURL = address -> Try.of(() -> new URL(address)).getOrElseThrow(ex -> { LOGGER.error(ex.getLocalizedMessage(), ex); throw new RuntimeException("Bad address", ex); - }); - - Function> serialize = param -> Try.of(() -> { - ObjectMapper objectMapper = new ObjectMapper(); - List deserializedData = objectMapper.readValue(param, new TypeReference>() {}); - return deserializedData.stream(); - }).getOrElseThrow(ex -> { - LOGGER.error("Bad Serialization process", ex); - throw new RuntimeException(ex); - }); + }); */ + + Function toURL = address -> { + try { + return new URL(address); + } catch (MalformedURLException ex) { + LOGGER.error(ex.getLocalizedMessage(), ex); + throw new RuntimeException("Bad address", ex); + } + }; + + Function> serialize = param -> { + try { + ObjectMapper objectMapper = new ObjectMapper(); + List deserializedData = objectMapper.readValue(param, new TypeReference>() {}); + return deserializedData.stream(); + } catch (Exception ex) { + LOGGER.error("Bad Serialization process", ex); + throw new RuntimeException("Bad Serialization process", ex); + } + }; Predicate godStartingByn = s -> s.toLowerCase().charAt(0) == 'n'; diff --git a/problems/src/main/java/info/jab/fp/latency/LatencyProblem02.java b/problems/src/main/java/info/jab/fp/latency/LatencyProblem02.java index 4d805eb..e666198 100644 --- a/problems/src/main/java/info/jab/fp/latency/LatencyProblem02.java +++ b/problems/src/main/java/info/jab/fp/latency/LatencyProblem02.java @@ -2,8 +2,8 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import io.vavr.Tuple2; -import io.vavr.control.Try; + +import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -50,16 +50,8 @@ public class LatencyProblem02 { LOGGER.error(ex.getLocalizedMessage(), ex); throw new RuntimeException("Bad address", ex); } - /* - Try.of(() -> - new URL(address)).getOrElseThrow(ex -> { - - }); - */ - }; - Function> serialize = (param) -> { try { ObjectMapper objectMapper = new ObjectMapper(); @@ -70,49 +62,49 @@ public class LatencyProblem02 { throw new RuntimeException("Bad Serialization process", ex); } }; - - /* - Try.of(() -> { - - }).getOrElseThrow(ex -> { - LOGGER.error("Bad Serialization process", ex); - throw new RuntimeException("Bad Serialization process", ex); - }); - */ - - Function buildWikipediaAddress = god -> Try.of(() -> - new URL(wikipediaPath + god)).get(); - - Function> getWikipediaContent = god -> - new Tuple2(god, fetch.apply(buildWikipediaAddress.apply(god)).length()); + + Function buildWikipediaAddress = god -> { + try { + return new URL(wikipediaPath + god); + } catch (MalformedURLException ex) { + throw new RuntimeException("Bad address", ex); + } + }; + + record Tuple2(String param1, Integer param2) {} + + Function getWikipediaContent = god -> { + String content = fetch.apply(buildWikipediaAddress.apply(god)); + return new Tuple2(god, content.length()); + }; public String JavaStreamSolution() { return Stream.of(greekGods) - .flatMap(toURL.andThen(fetch).andThen(serialize)) - .map(getWikipediaContent) - .peek(System.out::println) - .max((i, j) -> i._2.compareTo(j._2)) - .get()._1; + .flatMap(toURL.andThen(fetch).andThen(serialize)) + .map(getWikipediaContent) + .peek(System.out::println) + .max((i, j) -> i.param2().compareTo(j.param2())) + .get().param1(); } private static ExecutorService executor = Executors.newFixedThreadPool(10); - Function>> fetchAsync = address -> { + Function> fetchAsync = address -> { LOGGER.info("Thread: {}", Thread.currentThread().getName()); return CompletableFuture .supplyAsync(() -> getWikipediaContent.apply(address), executor) .exceptionally(ex -> { LOGGER.error(ex.getLocalizedMessage(), ex); - return new Tuple2(address + "-ERROR", 0); + return new Tuple2(address + "-ERROR", 0); }) - .completeOnTimeout(new Tuple2(address + "-TIMEOUT", 0), TIMEOUT, TimeUnit.SECONDS); + .completeOnTimeout(new Tuple2(address + "-TIMEOUT", 0), TIMEOUT, TimeUnit.SECONDS); }; public String JavaStreamSolutionAsync() { - List>> futureRequests = Stream.of(greekGods) + List> futureRequests = Stream.of(greekGods) .flatMap(toURL.andThen(fetch).andThen(serialize)) .map(fetchAsync) .collect(toList()); @@ -120,29 +112,29 @@ public String JavaStreamSolutionAsync() { return futureRequests.stream() .map(CompletableFuture::join) .peek(System.out::println) - .max((i, j) -> i._2.compareTo(j._2)) - .get()._1; + .max((i, j) -> i.param2().compareTo(j.param2())) + .get().param1(); } Function> fetchGods = s -> Stream.of(s) .flatMap(toURL.andThen(fetch).andThen(log).andThen(serialize)); - Function, Stream>> fetchWikipediaAsync = ls -> { - List>> futureRequests = ls + Function, Stream> fetchWikipediaAsync = ls -> { + List> futureRequests = ls .map(fetchAsync) .collect(toList()); return futureRequests.stream() .map(CompletableFuture::join) .map(s -> { - LOGGER.debug(s._1); + LOGGER.debug(s.param1()); return s; }); }; - Function>, String> max = ls -> ls - .max((i, j) -> i._2.compareTo(j._2)) - .get()._1; + Function, String> max = ls -> ls + .max((i, j) -> i.param2().compareTo(j.param2())) + .get().param1(); public String JavaStreamSolutionAsync2() { diff --git a/problems/src/main/java/info/jab/fp/latency/LatencyProblem03.java b/problems/src/main/java/info/jab/fp/latency/LatencyProblem03.java index 76c4ab9..79c5d68 100644 --- a/problems/src/main/java/info/jab/fp/latency/LatencyProblem03.java +++ b/problems/src/main/java/info/jab/fp/latency/LatencyProblem03.java @@ -2,7 +2,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import io.vavr.control.Try; import java.net.URL; import java.util.EnumMap; import java.util.List; @@ -17,6 +16,8 @@ import static info.jab.fp.latency.SimpleCurl.fetch; import static java.util.stream.Collectors.toUnmodifiableList; +import java.io.IOException; + import org.slf4j.LoggerFactory; import org.slf4j.Logger; @@ -42,11 +43,14 @@ public LatencyProblem03(EnumMap godMap, ExecutorService executor, this.TIMEOUT = TIMEOUT; } - Function toURL = address -> Try.of(() -> - new URL(address)).getOrElseThrow(ex -> { - LOGGER.error(ex.getLocalizedMessage(), ex); - throw new RuntimeException("Bad address", ex); - }); + Function toURL = (address) -> { + try { + return new URL(address); + } catch(IOException ex) { + LOGGER.error(ex.getLocalizedMessage(), ex); + throw new RuntimeException("Bad address", ex); + } + }; Function callAsync = url -> { @@ -62,14 +66,16 @@ public LatencyProblem03(EnumMap godMap, ExecutorService executor, ,TIMEOUT, TimeUnit.SECONDS).join(); }; - Function> serialize = param -> Try.of(() -> { - ObjectMapper objectMapper = new ObjectMapper(); - List deserializedData = objectMapper.readValue(param, new TypeReference>() {}); - return deserializedData.stream(); - }).getOrElseThrow(ex -> { - LOGGER.error("Bad Serialization process", ex); - throw new RuntimeException(ex); - }); + Function> serialize = (param) -> { + try { + ObjectMapper objectMapper = new ObjectMapper(); + List deserializedData = objectMapper.readValue(param, new TypeReference>() {}); + return deserializedData.stream(); + } catch(IOException ex) { + LOGGER.error("Bad Serialization process", ex); + throw new RuntimeException("Bad Serialization process", ex); + } + }; public List JavaStreamSolutionAsync(GODS god) { diff --git a/problems/src/main/java/info/jab/fp/latency/LatencyProblem04.java b/problems/src/main/java/info/jab/fp/latency/LatencyProblem04.java index f8bef04..a2afe25 100644 --- a/problems/src/main/java/info/jab/fp/latency/LatencyProblem04.java +++ b/problems/src/main/java/info/jab/fp/latency/LatencyProblem04.java @@ -4,11 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import info.jab.fp.euler.IEulerType3; -import io.vavr.CheckedFunction1; -import io.vavr.Function1; -import io.vavr.Function2; -import io.vavr.control.Option; -import io.vavr.control.Try; import static info.jab.fp.latency.SimpleCurl.fetch; import static info.jab.fp.latency.SimpleCurl.log; @@ -21,6 +16,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; +import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; @@ -45,18 +41,6 @@ public class LatencyProblem04 implements IEulerType3 { public static record Config(List list,Executor executor, int timeout) {}; - /* - @Data - @AllArgsConstructor - public static class Config { - - - private List list; - private Executor executor; - private int timeout; - } - */ - public static record ExchangeRate( long epoc, String from, @@ -76,33 +60,17 @@ public BigDecimal JavaSolution() { return null; } - Function toURLOld = address -> { + Function> toURL3 = address -> { try { - return new URL(address); + URL url = new URL(address); + return Optional.of(url); } catch (MalformedURLException ex) { LOGGER.error(ex.getLocalizedMessage(), ex); - throw new RuntimeException("Bad address", ex); + return Optional.empty(); } }; - Function1 toURL = address -> Try.of(() -> new URL(address)) - .getOrElseThrow(ex -> { - LOGGER.error(ex.getLocalizedMessage(), ex); - throw new RuntimeException("Bad address", ex); - }); - - CheckedFunction1 toURL2 = address -> new URL(address); - - Function1> toURL3 = address -> - Try.of(() -> new URL(address)) - .map(u -> Option.some(u)) - .onFailure(ex -> LOGGER.error(ex.getLocalizedMessage(), ex)) - .recover(ex -> Option.none()) - .get(); - - Function1, Optional> toOptional = option -> option.toJavaOptional(); - - Function2> fetchAsync = (address, config) -> { + BiFunction> fetchAsync = (address, config) -> { LOGGER.info("Thread: {}", Thread.currentThread().getName()); return CompletableFuture @@ -114,21 +82,22 @@ public BigDecimal JavaSolution() { .completeOnTimeout("[\"FETCH_BAD_RESULT_TIMEOUT\"]", config.timeout(), TimeUnit.SECONDS); }; - Function serialize = param -> Try.of(() -> { - ObjectMapper objectMapper = new ObjectMapper(); - ExchangeRate deserializedData = objectMapper.readValue(param, new TypeReference() {}); - return deserializedData; - }).getOrElseThrow(ex -> { - LOGGER.error("Bad Serialization process", ex); - throw new RuntimeException(ex); - }); + Function serialize = param -> { + try { + ObjectMapper objectMapper = new ObjectMapper(); + return objectMapper.readValue(param, new TypeReference() {}); + } catch (Exception ex) { + LOGGER.error("Bad Serialization process", ex); + throw new RuntimeException("Bad Serialization process", ex); + } + }; @Override public BigDecimal JavaStreamSolution() { Stream> requests = config.list().stream() .map(toURL3) - .filter(Option::isDefined) + .filter(Optional::isPresent) .map(o -> fetchAsync.apply(o.get(), config)); return BigDecimal.valueOf(requests diff --git a/problems/src/main/java/info/jab/fp/latency/LatencyProblem05.java b/problems/src/main/java/info/jab/fp/latency/LatencyProblem05.java index 5f3aa28..5c85433 100644 --- a/problems/src/main/java/info/jab/fp/latency/LatencyProblem05.java +++ b/problems/src/main/java/info/jab/fp/latency/LatencyProblem05.java @@ -4,13 +4,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import info.jab.fp.euler.IEulerType3; -import io.vavr.Function1; -import io.vavr.Tuple; -import io.vavr.Tuple2; -import io.vavr.control.Option; -import io.vavr.control.Try; + +import java.net.MalformedURLException; import java.net.URL; import java.util.List; +import java.util.Optional; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; @@ -22,6 +20,8 @@ import static info.jab.fp.latency.SimpleCurl.log; import static java.util.stream.Collectors.toList; +import java.io.IOException; + import org.slf4j.LoggerFactory; import org.slf4j.Logger; @@ -57,46 +57,53 @@ public List JavaSolution() { return null; } - Function1> toURL = address -> - Try.of(() -> new URL(address)) - .map(u -> Option.some(u)) - .onFailure(ex -> LOGGER.error(ex.getLocalizedMessage(), ex)) - .recover(ex -> Option.none()) - .get(); + Function> toURL = address -> { + try { + URL url = new URL(address); + return Optional.of(url); + } catch (MalformedURLException ex) { + LOGGER.error(ex.getLocalizedMessage(), ex); + return Optional.empty(); + } + }; - Function, CompletableFuture> fetchAsync = (tuple) -> { + record Tuple2(URL param1, Config param2) {} + + Function> fetchAsync = (tuple) -> { LOGGER.info("Thread: {}", Thread.currentThread().getName()); return CompletableFuture - .supplyAsync(() -> fetch.andThen(log).apply(tuple._1), tuple._2().executor()) + .supplyAsync(() -> fetch.andThen(log).apply(tuple.param1()), tuple.param2().executor()) .exceptionally(ex -> { LOGGER.error(ex.getLocalizedMessage(), ex); return "FETCH_BAD_RESULT"; }) - .completeOnTimeout("[\"FETCH_BAD_RESULT_TIMEOUT\"]", tuple._2.timeout(), TimeUnit.SECONDS); + .completeOnTimeout("[\"FETCH_BAD_RESULT_TIMEOUT\"]", tuple.param2().timeout(), TimeUnit.SECONDS); }; - Function> serialize = param -> Try.of(() -> { - ObjectMapper objectMapper = new ObjectMapper(); - List deserializedData = objectMapper.readValue(param, new TypeReference>() {}); - return deserializedData; - }).getOrElseThrow(ex -> { - LOGGER.error("Bad Serialization process", ex); - throw new RuntimeException(ex); - }); + Function> serialize = (param) -> { + try { + ObjectMapper objectMapper = new ObjectMapper(); + List deserializedData = objectMapper.readValue(param, new TypeReference>() {}); + return deserializedData; + } catch(IOException ex) { + LOGGER.error("Bad Serialization process", ex); + throw new RuntimeException("Bad Serialization process", ex); + } + }; Predicate godStartingByA = s -> s.toLowerCase().charAt(0) == 'a'; - Function1, List> validAddress = list -> list.stream() + Function, List> validAddress = list -> list.stream() .map(toURL) - .filter(Option::isDefined) - .map(Option::get) + .filter(Optional::isPresent) + .map(Optional::get) .collect(toList()); - Function1> loadBalance = config -> { + Function loadBalance = config -> { List validAddressList = validAddress.apply(config.list()); Integer index = new Random().nextInt(validAddressList.size()); - return Tuple.of(validAddressList.get(index), config); + return new Tuple2(validAddressList.get(index), config); }; @Override diff --git a/problems/src/main/java/info/jab/fp/latency/SimpleCurl.java b/problems/src/main/java/info/jab/fp/latency/SimpleCurl.java index a060b3d..2638e39 100644 --- a/problems/src/main/java/info/jab/fp/latency/SimpleCurl.java +++ b/problems/src/main/java/info/jab/fp/latency/SimpleCurl.java @@ -4,57 +4,53 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.util.Optional; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.vavr.control.Option; -import io.vavr.control.Try; - public class SimpleCurl { private static final Logger LOGGER = LoggerFactory.getLogger(SimpleCurl.class); - static Function fetch = url -> Try.of(() -> { - - LOGGER.debug("Thread: {}", Thread.currentThread().getName()); - LOGGER.debug("Requested URL: {}", url); - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .GET() - .uri(url.toURI()) - .build(); - - return client - .send(request, HttpResponse.BodyHandlers.ofString()) - .body(); - - }).getOrElseThrow(ex -> { - LOGGER.error(ex.getLocalizedMessage(), ex); - throw new RuntimeException("Bad Request", ex); - }); - + static Function fetch = url -> { + try { + LOGGER.debug("Thread: {}", Thread.currentThread().getName()); + LOGGER.debug("Requested URL: {}", url); + + HttpClient client = HttpClient.newHttpClient(); + HttpRequest request = HttpRequest.newBuilder() + .GET() + .uri(url.toURI()) + .build(); + + return client.send(request, HttpResponse.BodyHandlers.ofString()).body(); + } catch (Exception ex) { + LOGGER.error(ex.getLocalizedMessage(), ex); + throw new RuntimeException("Bad Request", ex); + } + }; - static Function> fetch2 = url -> Try.of(() -> { - LOGGER.debug("Thread: {}", Thread.currentThread().getName()); - LOGGER.debug("Requested URL: {}", url); + static Function> fetch2 = url -> { + try { + LOGGER.debug("Thread: {}", Thread.currentThread().getName()); + LOGGER.debug("Requested URL: {}", url); - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .GET() - .uri(url.toURI()) - .build(); + HttpClient client = HttpClient.newHttpClient(); + HttpRequest request = HttpRequest.newBuilder() + .GET() + .uri(url.toURI()) + .build(); - return Option.some(client - .send(request, HttpResponse.BodyHandlers.ofString()) - .body()); - }) - .onFailure(ex -> LOGGER.error("SimpleCURL Error: {}", ex.getLocalizedMessage(), ex)) - .recover(ex -> Option.none()) - .get(); + String responseBody = client.send(request, HttpResponse.BodyHandlers.ofString()).body(); + return Optional.of(responseBody); + } catch (Exception ex) { + LOGGER.error("SimpleCURL Error: {}", ex.getLocalizedMessage(), ex); + return Optional.empty(); + } + }; static Function log = value -> { LOGGER.debug("Response: {}", value); diff --git a/problems/src/test/java/info/jab/fp/euler/EulerProblem09Benchmark.java b/problems/src/test/java/info/jab/fp/euler/EulerProblem09Benchmark.java index 91e3ce2..d646dbf 100644 --- a/problems/src/test/java/info/jab/fp/euler/EulerProblem09Benchmark.java +++ b/problems/src/test/java/info/jab/fp/euler/EulerProblem09Benchmark.java @@ -4,8 +4,6 @@ import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; -import info.jab.fp.euler.EulerProblem09; - public class EulerProblem09Benchmark { @State(Scope.Thread) @@ -14,12 +12,7 @@ public static class St { Long limit = 1000l; } - //@Benchmark - public void JavaSolution(St st) { - st.problem.JavaSolution(st.limit); - } - - //@Benchmark + @Benchmark public void JavaStreamSolution(St st) { st.problem.JavaStreamSolution(st.limit); } diff --git a/problems/src/test/java/info/jab/fp/euler/utils/AnswerLoader.java b/problems/src/test/java/info/jab/fp/euler/utils/AnswerLoader.java index 7614bab..a60bf66 100644 --- a/problems/src/test/java/info/jab/fp/euler/utils/AnswerLoader.java +++ b/problems/src/test/java/info/jab/fp/euler/utils/AnswerLoader.java @@ -1,6 +1,5 @@ package info.jab.fp.euler.utils; -import io.vavr.Function1; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -8,6 +7,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.function.Function; public class AnswerLoader { @@ -32,7 +32,7 @@ private List loadFile() { return arr; } - Function1 getAnswer = row -> Arrays.stream(row.split(":")) + Function getAnswer = row -> Arrays.stream(row.split(":")) .skip(1) .map(part -> part.trim()) .findFirst() diff --git a/problems/src/test/java/info/jab/fp/latency/LatencyProblem03Test.java b/problems/src/test/java/info/jab/fp/latency/LatencyProblem03Test.java index f093072..de0f1f2 100644 --- a/problems/src/test/java/info/jab/fp/latency/LatencyProblem03Test.java +++ b/problems/src/test/java/info/jab/fp/latency/LatencyProblem03Test.java @@ -5,9 +5,9 @@ import com.github.tomakehurst.wiremock.WireMockServer; import info.jab.fp.euler.IEulerTestable; -import info.jab.fp.latency.LatencyProblem03; -import io.vavr.Tuple2; -import io.vavr.control.Try; + +import java.io.IOException; +import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.EnumMap; @@ -56,20 +56,18 @@ public void given_JavaSolution_when_executeMethod_then_expectedResultsTest() { } private List loadJsonFile(String file) { - - return Try.of(() -> { + try { ObjectMapper objectMapper = new ObjectMapper(); String readContent = new String(Files.readAllBytes(Paths.get(getClass().getClassLoader() .getResource("__files/" + file) .toURI()))); - List deserializedData = objectMapper.readValue(readContent, new TypeReference>() {}); - return deserializedData; - }) - .getOrElseThrow(ex -> { - //LOGGER.error("Problem loading JSON file", ex); + return objectMapper.readValue(readContent, new TypeReference>() {}); + } catch (IOException | URISyntaxException | NullPointerException ex) { + // You can log the exception if needed + // LOGGER.error("Problem loading JSON file", ex); throw new RuntimeException(ex); - }); + } } @Test @@ -114,29 +112,32 @@ public void given_JavaStreamSolution_when_executeMethod_then_expectedResultsTest LatencyProblem03 problem = new LatencyProblem03(godMap, executor, TIMEOUT); - Function>>> callAsync = god -> { + record Tuple2(Enum param1, List param2) {} + + Function> callAsync = god -> { //LOGGER.info("Thread: {}", Thread.currentThread().getName()); return CompletableFuture .supplyAsync(() -> { - return new Tuple2<>(god, problem.JavaStreamSolutionAsync(god)); + return new Tuple2(god, problem.JavaStreamSolutionAsync(god)); }, executor) .exceptionally(ex -> { //LOGGER.error(ex.getLocalizedMessage(), ex); - return new Tuple2<>(god, List.of("FETCH_BAD_RESULT")); + return new Tuple2(god, List.of("FETCH_BAD_RESULT")); }) .completeOnTimeout( - new Tuple2<>(god, List.of("FETCH_BAD_RESULT_TIMEOUT")) + new Tuple2(god, List.of("FETCH_BAD_RESULT_TIMEOUT")) ,TIMEOUT, TimeUnit.SECONDS); }; - Predicate>> assertResult = t -> extectedGodListMap.get(t._1).equals(t._2); + + Predicate assertResult = t -> extectedGodListMap.get(t.param1()).equals(t.param2()); //Then IntStream.rangeClosed(1, 256).boxed() .forEach(i -> { //LOGGER.info("Test iteration: {}", i); - List>>> futureCallList = List.of(GREEK, ROMAN, NORDIC).stream() + List> futureCallList = List.of(GREEK, ROMAN, NORDIC).stream() .map(callAsync) .collect(toList());