Menu
Coddy logo textTech

HashMap Methods

Parte da seção Lógica & Fluxo do Journey de C# da Coddy — lição 52 de 66.

Os métodos do HashMap fornecem maneiras poderosas de trabalhar com seus dados de dicionário. Vamos explorar alguns métodos comuns:

Verificar se uma chave existe no dicionário:

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);

bool hasApples = inventory.ContainsKey("apples");
// hasApples will be true

Obter todas as chaves do dicionário:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

// Obter todas as chaves
Dictionary<string, int>.KeyCollection keys = scores.Keys;
foreach (string name in keys)
{
    Console.WriteLine(name);
}

Obtenha todos os valores do dicionário:

// Get all values
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
    Console.WriteLine(score);
}

Remover um item do dicionário:

scores.Remove("Bob");
// Dictionary now only contains Alice's score

Limpar todos os itens:

scores.Clear();
// O dicionário agora está vazio

Obtenha o número de itens no dicionário usando .Count:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

int total = scores.Count;
Console.WriteLine(total);
// Output: 2
challenge icon

Desafio

Médio

Crie um método chamado ProcessDictionary que recebe um Dictionary<string, int> como argumento e realiza as seguintes operações:

  1. Imprima Keys: seguido de todas as chaves (uma por linha)
  2. Imprima Values: seguido de todos os valores (uma por linha)
  3. Verifique se o dicionário contém a chave "total" e imprima Contains 'total': True ou Contains 'total': False
  4. Remova a chave "temp" se ela existir
  5. Imprima Count: seguido da contagem de itens no dicionário após essas operações (use a propriedade .Count do dicionário)

Folha de consulta

Verifique se uma chave existe usando ContainsKey():

bool hasKey = dictionary.ContainsKey("keyName");

Obtenha todas as chaves de um dicionário:

Dictionary<string, int>.KeyCollection keys = dictionary.Keys;
foreach (string key in keys)
{
    Console.WriteLine(key);
}

Obtenha todos os valores de um dicionário:

Dictionary<string, int>.ValueCollection values = dictionary.Values;
foreach (int value in values)
{
    Console.WriteLine(value);
}

Remova um item usando Remove():

dictionary.Remove("keyName");

Limpe todos os itens usando Clear():

dictionary.Clear();

Obtenha o número de itens usando .Count:

int count = dictionary.Count;

Experimente você mesmo

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    static void ProcessDictionary(Dictionary<string, int> dict)
    {
        // Escreva seu código aqui
    }
    // Ignore o código principal, ele converte string para um HashMap
    static void Main(string[] args)
    {
        Dictionary<string, int> inputDict = new Dictionary<string, int>();
        
        // Read first line to check if it's JSON format
        string firstLine = Console.ReadLine();
        
        // Check if input is in JSON format
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Process JSON input
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Split by commas that are not inside quotes
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Extract key and value using regex
                    Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
                    if (match.Success)
                    {
                        string keyMatch = match.Groups[1].Value;
                        int valueMatch = int.Parse(match.Groups[2].Value);
                        inputDict.Add(keyMatch, valueMatch);
                    }
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            try
            {
                // Process traditional input format
                int n = int.Parse(firstLine);
                
                for (int i = 0; i < n; i++)
                {
                    string[] pair = Console.ReadLine().Split(':');
                    string key = pair[0];
                    int value = int.Parse(pair[1]);
                    inputDict.Add(key, value);
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Lógica & Fluxo