Implementation of graph in Java from Database
<p>What I have is 2 tables : </p>

<pre><code>    Users (id, name, lastname) 
    Friends (id1, id2)
</code></pre>

<p>Given these 2 tables, I need to be able to find the distance between 2 users d(id1,id2)</p>

<p>I defined a User class, that holds each of the user attribute in the table.</p>

<p>I need to build a graph. My data structure for the graph is </p>

<pre><code>     Map&lt;User, Set&lt;User&gt;&gt;
</code></pre>

<p>mapping a user to a set of his friends.
How am I building the graph ? I queried the db for the ids of all the users in the db. I got an </p>

<pre><code>   int[] userids
</code></pre>

<p>Then for each int in this array:</p>

<p>(1) I build a User object, fetching in the db the attributes of that user </p>

<p>(2) I query the Friends table in the db to have the ids of the friends of that user : </p>

<pre><code>    int [] friends
</code></pre>

<p>(3) for each int in this friends array, I build a User object fetching in the db the attributes of that user and add it to</p>

<pre><code>    Set&lt;User&gt; friends = new Set&lt;User&gt;();
</code></pre>

<p>Question 1 : Any ideas how to do this better ? It takes forever, given that I have 500 users, and 20000 entries in the Friends table ...</p>

<p>The big problem here is that when 2 users are the "same" in the database, they are referenced in differents objects in my graph !!</p>

<p>Which is messing up my distance algorithm. I start with a User u, get his Friends {f1,f2} , and when I wanna get the friends of friends using graph.get(f1) and graph.get(f2) I get null (for the reason stated in my problems, ie 1 db user in many different User objects)</p>

<p>I need to find a way to build my graph such that 1 given user say (1, John, Doe) is referenced in one and only User object in the heap ...</p>

<p>Question 2 : How ??</p>

<p>Thank you so much</p>

<p><a href="http://stackoverflow.com/questions/7329427/help-with-java-graph-implementation">Help with Java Graph Implementation</a></p>
