Loading collection data...
Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.
Get started now by creating a new collection.
getOrDefault(key, defaultValue)
utlity method on Map will try to retrieve the value under key specified in first argumentkey
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 argumentdefaultValue
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.
how does it work
This comment is hidden because it contains spoiler information about the solution
This comment is hidden because it contains spoiler information about the solution
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.