How to create a new key-value pair in a Map with Java

1 Answer

0 votes
import java.util.Map;
import java.util.Arrays;
import java.util.HashMap;

public class MyClass {
    public static void main(String args[]) {
        Map<String, Integer> map = new HashMap<>();
        
        map.put("java", 4);
        map.put("c#", 6);
        map.put("c", 2);
        
        Object[] arr = map.entrySet().toArray();
        System.out.println(Arrays.toString(arr));
        
        for (Map.Entry<String, Integer> entry:map.entrySet()) {
            System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
        }
    }
}
       
       
       
       
/*
run:
       
[c#=6, java=4, c=2]
key: c# value: 6
key: java value: 4
key: c value: 2
       
*/

 



answered Oct 7, 2023 by avibootz

Related questions

1 answer 111 views
2 answers 214 views
2 answers 231 views
2 answers 166 views
1 answer 137 views
1 answer 142 views
...