java - Add value to key in hashmap -
I have a hashup of my custom object and each user has several values I found out how to create a map and a Put the value on the key, but there is a need for help with this type of check (pseudo code):
If the key is present then add another value for the key and add the key and value < / code> I currently have: Maps & lt; String, custom & gt; Map = new hashmap & lt; String, custom & gt; (); {Map.put (p.getUser (), p) for (custom: data); } Output: user1 / package.class@1231412 user2 / package.class@12fwf3 user3 / package.class @ Dc238d Code to get the output: for (map entry.lt; string, custom & gt; Entry: map.entrySet ()) {System.out.println (entry.getKey () + "/" + entry.getValue ()); } Requirement: user1 / package.custom@1231412, package.custom@vfee, package.custom@2riopj User2 / package.custom@12fwf3, package.custom@cwfc3 user3 / package.custom@324rrf, package.custom@23d, package.custom@cvewff2 I will eventually repeat this on each Map and use them to get objects, but the key changes itself, so I do not have all my information.
It looks like you're using Maps & lt; String, list & lt; custom & gt; & Gt; to use. For each key, check whether a mapping already exists, if this case adds custom to the mapped list with this key, otherwise create a new mapping and add it.
for (custom page: data) {list & lt; custom & gt; L = map.get (p.getUser ()); If (L == empty) {L = New Arrielast & lt; & Gt; (); Map.put (p.getUser (), l); } L.add (p); } If you are using Java 8, the above arguments can be simplified on:
Maps & lt; String, list & lt; Custom & gt; & Gt; Map = data.stream () .collect (collectorsghorfing bye (custom :: eucusur)); In the end if you are familiar with the lava of libraries (and if you do not even give my advice), look at the class, this is a collection, which can map each key to multiple values. Apart from this, it is good to follow naming conventions.
Comments
Post a Comment