0

I have a List, and I am trying to fill a HashMap in a for or loop

HashMap<String, String> h = new HashMap<String, String>();

for(String a : tempFindings) //tempFindings is a List<String>
{
    String[] parts = a.split("\\.");
    String part1 = parts[0]; 
    String part2 = parts[1];
    h.put(part2, part1);
}

in each loop it rewrites the values in the HashMap but I want all my list in it. how can I do it?

Edited:

HashMap<String[], String[]> h = new HashMap<String[], String[]>();
                    String[] part2 = new String[100];
                    String[] part1 = new String[100];
                    int n = 0;
                    for(String a : tempFindings)
                    {
                        String[] parts = a.split("\\.");
                        part1[n] = parts[0]; 
                        part2[n] = parts[1];
                        n++;
                        
                    }
                    h.put(part2, part1);

I tried to use String[], ut ater the loop when I assign the String[] values, key and alue is null any suestion?

user3122648
  • 887
  • 2
  • 8
  • 21
  • use `HashMap>`? [putIfAbsent](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#putIfAbsent-K-V-) would help to make a simple code –  Jul 15 '20 at 18:56

1 Answers1

1

A hashMap doesn't allow duplicate keys. So if your part2 String is repeated, the hashMap will overwrite the first value with the new one. To stop this, you could make a hashMap<String, String[]> and then add all of the different values to an array before adding that array to the hashMap.

sabraship
  • 99
  • 1
  • 8