0

Do we have any other way to add an element into Map without using put() in Java? If there are other ways, how do we do it?

Map<String,String> map = new HashMap<String,String>();
map.put("hi","HI");

How can we add without using put() in this case?

Jacob
  • 14,463
  • 65
  • 207
  • 320
Eshwar
  • 19
  • 5
  • 4
    you mean with a shovel? –  Mar 01 '15 at 15:23
  • there exist a method called putAlll. But that is not exactly the same http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#putAll(java.util.Map) – Thusitha Thilina Dayaratne Mar 01 '15 at 15:24
  • You can use the methods `replace` and `putIfAbsent` ... *if* you're using java 8. – fabian Mar 01 '15 at 15:30
  • 2
    You probably should not be using `Map` if you want other ways of adding an element. – tourniquet_grab Mar 01 '15 at 15:36
  • If you're asking for `Map` literals (something like `Map map = {1="Hi", 2="Hello"};`) the answer is that you just can't do that. Lots of tedious calls to `put` is unfortunately how you have to initialise a `Map` at the moment. – Paul Boddington Mar 01 '15 at 16:07
  • What's wrong with put()? Why do you want to avoid using it? Why don't you read the javadoc, which would answer this question? – JB Nizet Mar 01 '15 at 16:24
  • You can specify initial content in the constructor. But internally it all boils down to some form of put, of course. – eckes Mar 02 '15 at 00:23

2 Answers2

1

put and putAll are the only two methods for adding new hash entries in Java. If you're looking for a Ruby or Python style way of doing it such as hash['x'] = 'hello world';, then you are going to need to use a JVM language like JRuby or Groovy.

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
0

There is no way to change HashMap content without calling put() or other mutation methods. Probably, you are looking for double brace initialization. For more info, see this answer.

Community
  • 1
  • 1
Everv0id
  • 1,862
  • 3
  • 25
  • 47