Results 1 to 2 of 2
Thread: Double Iteration Over a Hashmap
- 12-01-2010, 12:33 AM #1
Member
- Join Date
- Nov 2010
- Posts
- 1
- Rep Power
- 0
Double Iteration Over a Hashmap
I'm using a hashmap to hold multiple Player objects for a multi-player game. In one section of my code, I need to check the distances from each player to every other player. I learned how to iterate over a hashmap, but things seem to go very wrong when I try two levels of nested iteration over the same map.
I am assuming what I am doing here is incorrect. What would be the simplest method to perform a two level nested iteration on a hashmap?Java Code:Iterator a = player.entrySet().iterator(); while (a.hasNext()) { Map.Entry aMe = (Map.Entry)a.next(); Player myAPlayer = (Player) aMe.getValue(); Iterator b = player.entrySet().iterator(); while (b.hasNext()) { Map.Entry bMe = (Map.Entry)b.next(); Player myBPlayer = (Player) bMe.getValue(); // First make sure that myAPlayer and myBPlayer are not the same, // then do something here with both players. } }
Thank you in advance for your time.
-
I am no pro at this, and don't know if there is a standard way to do this, but one way that may work is to create a List out of the map's keySet, and then iterate over the list in a pair of nested for loops. For e.g., if the Map Keys and Values were Strings and this were a generic map:
Java Code:List<String> list = new ArrayList<String>(map.keySet()); for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { System.out.printf("[%s, %s]%n", map.get(list.get(i)), map.get(list.get(j))); } }
Similar Threads
-
double a * double b = weird output
By GPB in forum New To JavaReplies: 3Last Post: 03-26-2010, 10:40 AM -
How to create a new HashMap from a HashMap entries of other methods
By pandeyalok in forum Advanced JavaReplies: 7Last Post: 12-08-2009, 07:17 PM -
Arrays, Iteration and selection (Cache)
By dietgal in forum New To JavaReplies: 17Last Post: 10-11-2008, 07:44 AM -
Enum Iteration
By A.Russell in forum New To JavaReplies: 1Last Post: 08-15-2007, 12:17 PM -
iteration on huge amount of files in a folder
By tshaked in forum Advanced JavaReplies: 1Last Post: 08-07-2007, 07:08 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks