Results 1 to 2 of 2
  1. #1
    Gusy is offline Member
    Join Date
    Nov 2010
    Rep Power

    Default 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.

    Java Code:
    Iterator a = player.entrySet().iterator();
    while (a.hasNext())
    	Map.Entry aMe = (Map.Entry);
    	Player myAPlayer = (Player) aMe.getValue();
    	Iterator b = player.entrySet().iterator();
    	while (b.hasNext())
    		Map.Entry bMe = (Map.Entry);
    		Player myBPlayer = (Player) bMe.getValue();
    		// First make sure that myAPlayer and myBPlayer are not the same,
    		// then do something here with both players.
    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?

    Thank you in advance for your time.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Blog Entries
    Rep Power


    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

  1. double a * double b = weird output
    By GPB in forum New To Java
    Replies: 3
    Last Post: 03-26-2010, 10:40 AM
  2. Replies: 7
    Last Post: 12-08-2009, 07:17 PM
  3. Arrays, Iteration and selection (Cache)
    By dietgal in forum New To Java
    Replies: 17
    Last Post: 10-11-2008, 07:44 AM
  4. Enum Iteration
    By A.Russell in forum New To Java
    Replies: 1
    Last Post: 08-15-2007, 12:17 PM
  5. iteration on huge amount of files in a folder
    By tshaked in forum Advanced Java
    Replies: 1
    Last Post: 08-07-2007, 07:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts