I'm not sure how to put the <key, value> value in Java HashMap with a repeat statement.

Asked 1 years ago, Updated 1 years ago, 130 views

I learned about Java this time.

I was studying hashmap, but I wondered if I could put the key value as a repeating sentence.

public static void main(String[] args)
{
    HashMap<string, Integer> map1 = new HashMap<String, Integer>();

    for(int i =0; i<100; i++)
    {
        map1.put("i",i+1);
    }

System.out.println(map1);
}

I did it like this The result is also (1,100). That's all.

Can't you do the string by turning the repetition sentence ++1 each?

The price I want is (1,1) (2,2) (3,3) .... (100, 100) is taken on the console.

If I try to put the key one by one, it takes too long, so is there a good way?

Thank you for your interest.

java hashmap key

2022-09-21 20:08

1 Answers

I don't understand the code. I turn the repeated door 100 times and put() on the map, but the key is always the same, so 99 times is overwritten.

public static void main(String[] args) {
    Map<String, Integer> map = new HashMap<>();

    for (int i = 0; i < 100; i++) {
        map.put(String.valueOf(i), i++);
    }

    System.out.println(map);
}

Is this what you want?


2022-09-21 20:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.