Skip to content

Instantly share code, notes, and snippets.

@lpenaud
Created October 15, 2024 13:52
Show Gist options
  • Save lpenaud/d98cdd7c5ffa09ac504bcc679ecba8e5 to your computer and use it in GitHub Desktop.
Save lpenaud/d98cdd7c5ffa09ac504bcc679ecba8e5 to your computer and use it in GitHub Desktop.
HashMap number mapping

From number of mapping

Java 19 add newHashMap(int) to HashMap and LinkedHashMap.

See: Java doc HashMap

Calculate capacity from load factory

private static final short DEFAULT_LOAD_FACTOR = .75;

public static int calculateMapCapacity(int numMappings) {
  return (int) Math.ceil(numMappings / (double) DEFAULT_LOAD_FACTOR);
}

public static <K, V> HashMap<K, V> newHashMap(final int numMappings) {
  return new HashMap<>(calculateMapCapacity(numMappings), DEFAULT_LOAD_FACTOR);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment