CodeGym /Java 博客 /随机的 /如何更新 HashMap 中现有键的值
John Squirrels

San Francisco

如何更新 HashMap 中现有键的值

``````
HashMap<Key, Value> name
``````

``````
Map<Integer, String> names = new HashMap<Integer, String>();
names.put(1, "Stan");
names.put(2, "Kyle");
names.put(3, "Kenny");
names.put(4, "Cartman");
``````

``````
Map<Integer, String> names = new HashMap<Integer, String>() {
{
put(1, "Stan");
put(2, "Kyle");
put(3, "Kenny");
put(4, "Cartman");
}
};
``````

``````
Map<Integer, String> names = new HashMap<>(Map.of(1, "Stan", 2, "Kyle", 3, "Kenny", 4, "Cartman"));
``````

``````
names.put(3, "Butters");
``````

``````
{1=Stan, 2=Kyle, 3=Butters, 4=Cartman}
``````

``````
import java.util.HashMap;

public class HashMapUpdKey {
public static void main(String[] args) {
Map<Integer, String> names = new HashMap<>(Map.of(1, "Stan", 2, "Kyle", 3, "Kenny", 4, "Cartman"));
names.put(5, "Kenny");
System.out.println(names);
}
}
``````

``````
{1=Stan, 2=Kyle, 3=Kenny, 4=Cartman, 5=Kenny}
``````

``````
//easy replacement example
import java.util.HashMap;

public class HashMapUpdKey {
public static void main(String[] args) {
Map<Integer, String> names = new HashMap<>(Map.of(1, "Stan", 2, "Kyle", 3, "Kenny", 4, "Cartman"));

System.out.println(names.remove(3)); //Update value of the key: Removing “old” Kenny and print out deleted value

System.out.println(names);
}
}
``````

``````
names.put(5, names.remove(3));
``````

TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION