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?
You can try this:
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:
You can easily do it using Java 8's
stream
API, below is an example: