Ad
  • Default User Avatar

    getOrDefault(key, defaultValue) utlity method on Map will try to retrieve the value under key specified in first argument key when it exists it will return the value and then you just increment that count by one, in other case when key is not existing in the map it will put the new key-value pair with value defined in the second argument defaultValue which in our case is 0 and then increment it by one. This allows you to completelly skip if statement with .contains(key) call.

    Check my solution and look for imperative style method if you want exact code.

    Theres considerable performance improvement over the if statements as well, but only in larger datasets which does not really apply for this Kata, but its considered good practice. To understand why requires deeper knowledge about JVM and how the JIT works in Java, you can read about predictive branching in java if you want to know more about that. In my solution you can see both imperative approach and declarative using Java Streams API, which one of those will be more performant on the large datasets I cant really say because I didnt run any benchmarks on these, but if I should make a guess I would say Streams with parallelization using parallelStream would result in faster operations.

    When it comes to performance always remember to judge it only if its actually problem for you, for small application most of the approaches are absolutely valid, but when you encounter bottlenecks or bad performance in larger application then consider optimizing.

  • Default User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Default User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Default User Avatar

    Even when declarative approach is very keen on the eye it introduces a large overhead compared to just using sort with imperative looping... in my case its around 26ms overhead, compared to 0 abstraction solution that is under half of millisecond, its arround 8000% increase in execution time... For more info check my solution.