0

Can I build a Map more succinctly? Sort of like Sets.cartesianProduct(set1, set2, ... ), I'd like a one-liner to build a map with empty, initialized, mutable Lists. The following code is just for illustration.

Map<MyEnumeration, List<String>> answer = new HashMap<>();
for (MyEnumeration enum : MyEnumeration.values()) {
    answer.put(enum, new ArrayList<String>());
}

I like other people's [tested] code. This isn't quite right, this is really about how to instantiate things and despite the title, this is really a question about generics.

Community
  • 1
  • 1
user121330
  • 199
  • 1
  • 10
  • 1
    Well, that would depend on how you're getting the list? – Rohit Jain Apr 15 '15 at 16:29
  • @RohitJain Right here, I want a new list, but if I had a collection of Lists, and I could do a cartesian product-like operation, that'd work. – user121330 Apr 15 '15 at 16:30
  • Are you using Java 8? – Rohit Jain Apr 15 '15 at 16:33
  • @RohitJain Java 7 :( – user121330 Apr 15 '15 at 16:35
  • Then there is no one-liner I'm afraid. – Rohit Jain Apr 15 '15 at 16:40
  • @RohitJain 'No' is a perfectly acceptable answer - I'll upvote and accept it if you list a few plausible packages (com.​google.​common.​collect.​Maps) etc... which don't contain this operation. Conversely, if it's possible in Java 8 but not 7, I'll upvote and accept if you outline that code as well. – user121330 Apr 15 '15 at 16:41
  • The only alternative I can offer you is to create your own `Map` class by inheriting from `AbstractMap`. In there you can create a constructor that would take your enumeration and create the keys from it as well as generating the `List` objects for each key. As far as JDK goes, there is no `Map` implementation which does what you describe in your post. –  Apr 15 '15 at 16:42
  • @I.K. I thought about that, but it defeats the purpose of the one liner that's been tested by smarter people with more use-cases. – user121330 Apr 15 '15 at 16:43
  • I would hardly say that *'been tested by smarter people...'* is the purpose of one-liners. But if you are looking for code in the JDK that does this, then, I repeat, you are out of luck. Unless like I said, you build your own custom Map class. –  Apr 15 '15 at 16:53
  • @I.K. Brevity (clarity) is also a purpose, but as I said, 'No, and here's why and what I checked' is a perfectly acceptable answer which I will post if nobody else does. I appreciate the power of overriding methods, but a static factory would also suffice. – user121330 Apr 15 '15 at 17:02
  • are you open to using the Guava library? –  Apr 15 '15 at 17:31
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75318/discussion-between-user121330-and-i-k). – user121330 Apr 15 '15 at 17:48

1 Answers1

1

You can use EnumMap.

For example:

Map<MyEnumeration, List<String>> answer = new EnumMap(MyEnumeration.class);
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147