data structures - Java HashMap indexed on 2 keys -


I want to create a hashmap in Java for users with priorities. It would be easy to do this in a database, but unfortunately I could not use the database. What I need is a way to find a user by name in a hashmap, and to find all users with a certain interest (eg golf). If I delete a user, all his interests should be removed.

Anyone knows a good way to create this data structure?

Do you know that you really need a second index, you will find that every user's search is fast Is enough, unless you have millions of users.

In the following example, 1,000 users take 51 micros-seconds to scan. It takes 557 microbe-seconds to scan 10,000 users.

I do not suggest optimizing the collection unless you know that it will make a difference.

  import java.util. *; Import java.io * *; Public Segment Test Expector {Public Static Zero Main (String [] Args throws IOException {Map & lt; String, user & gt; Users = New LinkedHashp & lt; String, User & gt; (); Generated user (user, 1000, 0.1); // to get excited. Int calculation = 10000; (Int i = 0; i & lt; c; i ++) for getAllUsersWithInterest (users, interest.Golf); Long start = System.nanoTime (); (Int i = 0; i & lt; c; i ++) for getAllUsersWithInterest (users, interest.Golf); Long = system.nanoTime () - start; System.out.printf ("Average Search Time%, D Micro-Second% n", Time / Calculation / 1000); } Private fixed set & lt; Users & gt; GetAllUsersWithInterest (Map & lt; String, User & gt; Users, Interest Golf) {Set & lt; Users & gt; Ret = new linked H.2Sset & lt; Users & gt; (); (User user: users.values ​​()) {if (user.interests.contains (golf)) ret.add (user); } Return return; } Private static zero generated user (map & lt; string, user & gt; user, integer number, double interest inGolf) {random random = new random (); While (users.size () & lt; count) {string name = long.stosting (rand.nextLong (), 36); EnumSet & LT; Interest & gt; Interests = RAND NXFlot () & lt; Interest InGolf? EnumSet.of (interest.Golf): EnumSet.noneOf (interest category); Users.put (name, new user (name, interests)); }} Stable class user {name of the private last string; Private Final Set & lt; Interest & gt; Interests; User (string name, set & lt; interest & gt; interests) {this.name = name; This.interests = Interests; }} Enum Interest {Golf}}  

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -