-1

I have a final map which is initialized in the constructor. I am adding the data to map in loop in addData() method. Is there a good way to add data to final map instead of using loop? Is there any feature in guava?

class TestClass {
 private final Map<K,v> map1;

 public TestClass() {
  map1 = Maps.newHashMap();
 }

 public void addData(Map<K,V> data) {
  for(Entry<K,V> entry : data.entrySet()) {
    map1.put(entry.getKey(), entry.getValue());
  }
 }
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
user3222372
  • 352
  • 3
  • 20
  • 1
    Your little code snippet is full of compile errors. "Class" must be "class", "provate" must be "private", the type parameters are not declared. Additionally, you should read the [Map API](http://docs.oracle.com/javase/8/docs/api/java/util/Map.html), especially the [`putAll`](http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#putAll-java.util.Map-) method. Voting to close. – Seelenvirtuose Jul 08 '14 at 06:41
  • Other than compilation errors mentioned above, this question has already been posted before, I personally believe this was the best answer but you can also take a look at the other answers on this post. http://stackoverflow.com/a/7194798/1906826 – Alex Jul 08 '14 at 06:42

1 Answers1

1

You overlooked putAll

map1.putAll(data);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138