• Post Reply Bookmark Topic Watch Topic
  • New Topic

Trying to Get Rid of the Middle Man on Maps  RSS feed

 
Kevin Simonson
Ranch Hand
Posts: 223
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just wrote a piece of Java code to test another piece of Java code. I wanted to create a static Map object that maps Strings to Integers, but I didn't see any way to do that in place, so to speak. So instead I created a static array and used code to transform that array into the desired Map as follows:

and then I have a stripped down version of the test code as follows:

Is there a way to declare a static Map object and assign it values right there where I declare it, like I did for TEST_CASES above? In other words, is there a way to get around the middleman that the array is and just set up a Map object there so I can use it?
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kevin Simonson wrote:Is there a way to declare a static Map object and assign it values right there where I declare it, like I did for TEST_CASES above? In other words, is there a way to get around the middleman that the array is and just set up a Map object there so I can use it?


Yes.

To declare it:



To initialize it, use a static initializer:



I find it hard to say what code you should insert there; looking at your code, I can't really tell what part of it is actually required for the code and what part is your "middleman" workaround.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For Java 9 there is a (proposed) change that lets you create unmodifiable Maps (and Lists and Sets) using static methods on the interface. This would be overloaded to support 0 to 10 (inclusive) key/value pairs, plus an additional varargs overload for any number of entries. In short, it would look like this:
 
Kevin Simonson
Ranch Hand
Posts: 223
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:For Java 9 there is a (proposed) change that lets you create unmodifiable Maps (and Lists and Sets) using static methods on the interface. This would be overloaded to support 0 to 10 (inclusive) key/value pairs, plus an additional varargs overload for any number of entries. In short, it would look like this:

Intriguing. This is kind of what I was looking for. Too bad it's not available in Java 8. Is entry( st, i) a method call then, or does entry become a new reserved word, in this suggested change?
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a method call that creates an immutable Map.Entry implementation.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!