Skip to content

Is there any function like computeIfAbsent in Java #67376

Answered by gfoidl
tasty0tomato asked this question in Q&A
Discussion options

You must be logged in to vote

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<st…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@tasty0tomato
Comment options

@Joe4evr
Comment options

Answer selected by tasty0tomato
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants