Is there any function like computeIfAbsent in Java #67376
Answered
by
gfoidl
tasty0tomato
asked this question in
Q&A
-
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#computeIfAbsent-K-java.util.function.Function-
And there was a similar question in Stack, but unfortunately, there wasn't an answer. |
Beta Was this translation helpful? Give feedback.
Answered by
gfoidl
Mar 31, 2022
Replies: 1 comment 2 replies
-
You can write it in C# with very efficiently. See the following example: using System.Runtime.InteropServices;
Dictionary<int, List<string>> buckets = new();
AddToBucket(buckets, "Hello");
AddToBucket(buckets, "World");
AddToBucket(buckets, "C# rocks :-)");
foreach (KeyValuePair<int, List<string>> bucket in buckets.OrderBy(b => b.Key))
{
Console.WriteLine($"bucket: {bucket.Key}");
foreach (string item in bucket.Value)
{
Console.WriteLine($"\t{item}");
}
}
static void AddToBucket(Dictionary<int, List<string>> buckets, string word)
{
ref List<string>? list = ref CollectionsMarshal.GetValueRefOrAddDefault(buckets, word.Length, out _);
list ??= new List<string>();
list.Add(word);
} very efficiently. Different approach: static void AddToBucket(Dictionary<int, List<string>> buckets, string word)
{
List<string> entries = buckets.GetValueOrDefault(word.Length, new List<string>());
entries.Add(word);
buckets[word.Length] = entries;
} |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
tasty0tomato
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can write it in C# with very efficiently. See the following example: