2

I want to pass list of key-values pairs into my function.

I can do this by following:

HashMap<String, String> params = new HashMap<>();
params.put("param1", value1);
params.put("param2", value2);
foo(params);

But there are 4 lines of code. And my foo function will be called in many times in my code, so it becomes hard to read.

Can we decrease number of lines in this call?

  1. Is there a way to write foo([("param1", value1), ("param2", value2)])?
  2. Maybe Java standard classes have constructors to pass there several elements?
  3. Or can we write some factory class, that will create HashMap in less lines of code?
Artem Mostyaev
  • 3,874
  • 10
  • 53
  • 60
  • You Can pass in a flat list and convert it to a map in your method. – Thorbjørn Ravn Andersen May 18 '16 at 09:47
  • @ThorbjørnRavnAndersen Will it work below Java 8? Can you give a short example or link? – Artem Mostyaev May 18 '16 at 09:48
  • 1. [No collection literals](http://mail.openjdk.java.net/pipermail/lambda-dev/2014-March/011938.html) for now. 2. [Probably soon](http://openjdk.java.net/jeps/269). 3. Sure. Should be pretty trivial? – aioobe May 18 '16 at 09:52
  • 1
    @aioobe I am not sure why this question was reopened. The linked question has a lot of answers showing how to initialize a Map in a single line, using various libraries or tricks, which is what this question is asking. What about this other one? http://stackoverflow.com/questions/6802483/how-to-directly-initialize-a-hashmap-in-a-literal-way?lq=1 – Tunaki May 18 '16 at 09:54
  • 1
    I think what @ThorbjørnRavnAndersen is suggestion is that you do `Arrays.asList("param1", value1, "param2", value2)`. – aioobe May 18 '16 at 09:54
  • @Tunaki, that's a much better question to refer to here imo. – aioobe May 18 '16 at 09:58
  • 1
    @Tunaki The linked question shows an example of static map. I've looking at answers there for 15 minutes already, but can't find the appreciate answer. – Artem Mostyaev May 18 '16 at 09:58
  • @ArtemMostyaev, do you feel your question is properly answered by [How to directly initialize a HashMap (in a literal way)?](http://stackoverflow.com/questions/6802483/how-to-directly-initialize-a-hashmap-in-a-literal-way?lq=1)? – aioobe May 18 '16 at 09:59
  • @aioobe Yes, that's was I've searched. But I couldn't find it while Googling, so maybe my title will help someone to find that. – Artem Mostyaev May 18 '16 at 10:05

0 Answers0