Skip to content
Advertisement

Java invert a map

I need to invert an original map. which type is <Integer, String>, like {1 = A, 2 = A, 3 = B....}. I want to create a new map which is String to ArrayList because if 1 = A, and 2 = A, than I want to have something like this: A = [1, 2].

So how can I do that?

Advertisement

Answer

You can try this:

JavaScript

So, let’s say HashMap<Integer, String> original is {1=A, 2=B, 3=C, 4=A}, then you will get {A=[1, 4], B=[2], C=[3]}.

EDIT: If you want a more generic version, as @Mr.Polywhirl has suggested, you can use:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement