Results 1 to 14 of 14
Like Tree2Likes
  • 1 Post By Norm
  • 1 Post By Whisperer

Thread: Get values & keySet from an embedded HashMap

  1. #1
    Whisperer is offline Member
    Join Date
    Aug 2011
    Location
    Cornwall, UK
    Posts
    22
    Rep Power
    0

    Default Get values & keySet from an embedded HashMap

    I have a HashMap with a keyset of Strings and an ArrayList of integer values, the integer values can not be sorted.

    I am required to produce a collection of similar HashMaps using the name of each as a new keyset and the object as the value - I have chosen a treeset so that the names can be sorted automatically.

    My problem is simply how do I dig down to get the HashMap keylist and values from the Object stored in the TreeMap referenced by A below?

    Java Code:
    Set<String> a = A.keySet();
    Object obj = A.values(); //Is this correct?
    I now want to get at the keySet() and values in the HashMap referenced by obj
    TIA Whisperer

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,589
    Rep Power
    23

    Default

    Can you provide a small,sample program that compiles and shows the problem?
    JeffGrigg likes this.

  3. #3
    JeffGrigg is offline Member
    Join Date
    Aug 2011
    Posts
    95
    Rep Power
    0

    Default

    The statement 'Object obj = A.values();' probably does not give you anything you can use -- because you don't know what keys go with those values.

    Here are two typical ways of looping through all the items in a Map:
    Java Code:
    		for (String key : someMap.keySet()) {
    			System.out.println(key + " = " + someMap.get(key));
    		}
    and
    Java Code:
    		for (Map.Entry<String, String> entry : someMap.entrySet()) {
    			System.out.println(entry.getKey() + " = " + entry.getValue());
    		}

  4. #4
    Whisperer is offline Member
    Join Date
    Aug 2011
    Location
    Cornwall, UK
    Posts
    22
    Rep Power
    0

    Default

    Thanks Jeff,
    I will have a look at those tomorrow.
    Whisperer

  5. #5
    Whisperer is offline Member
    Join Date
    Aug 2011
    Location
    Cornwall, UK
    Posts
    22
    Rep Power
    0

    Default

    I had got 75% the way preparing a sample programme when I realised my area of concern had been caused by my 'extend'ing one class from another when it should not have been so.

    Sorry to have wasted your time Norm and Jeff and thanks for your rapid responses.

    Whisperer
    JeffGrigg likes this.

  6. #6
    Whisperer is offline Member
    Join Date
    Aug 2011
    Location
    Cornwall, UK
    Posts
    22
    Rep Power
    0

    Default Wrong again!

    OK, my recognition of the 'extend' error has certainly simplified elements of the programme but I cannot achieve my objective of 'getting the values & keyset from an embedded HashMap' the following code produces the Town Class and does its job (I think). I am using BlueJ v 3.04 and Java 1.060_07
    Java Code:
    Removed by author
    The next code produces the problem Class NationalRegister working up to but not including the final output:
    Java Code:
    import java.util.*;
    
    /**
     * Maintains a sorted list of accomodation requirements by town
     * @version 1.13.08.11
     */
    public class NationalRegister
    {
       private TreeMap<String, Object> allTowns;
    
       /**
        * Constructor for objects of class NationalRegister
        */
       public NationalRegister()
       {
          super();
          allTowns = new TreeMap<String, Object>();
       }
    
       /**
        * Places a town and its requirements into the National Register
        */
       public void addTown(Town town)
       {      
          allTowns.put(town.getTownName(), town);
       }
       
       /**
        * Prints the towns, the house types and the applicants
        * signed up for each house
        */
       public void printAllRecords()
       {
          Set<String> towns = allTowns.keySet();       
          Object obj = allTowns.values();
          for (String townName : towns)
          {
             List<Integer> townDetails = new ArrayList<Integer>();
    //         townDetails = towns.get(townName);      
                
          }
       }  
    }
    This is the testcode I used:
    //TESTCODE USED: - CREATES TWO TOWNS
    String[]accomType = {"1 Bed Flat", "2 Bed Flat", "1 or 2 Bed House","3 Bed House ", "4+ Bed House"};
    Integer[][]appNo = {{75, 60, 300}, {160, 710, 45,207},{221, 77, 65}, {101, 37}, {141, 250}};
    Town andover = new Town("Andover");
    andover.recordApplications(accomType, appNo);
    Integer[][]appNo = {{720, 25, 250}, {55, 128, 770}, {177, 160, 220},{121}, {270, 77}};
    Town belfast = new Town("Belfast");
    belfast.recordApplications (accomType, appNo);

    //LOADS THE TOWNS TO THE NATIONAL REGISTER
    NationalRegister nr = new NationalRegister ();
    nr.addTown(andover);
    nr.addTown(belfast);

    //THE EVENTUAL OUTCOME DOES NOT WORK
    nr.printAllRecords();
    MY PROBLEM starts with what I am trying to do in the incomplete method printAllRecords()
    The way I see it is that I need to dig down to the bottom of the 5 Inspector windows below to get the applicants – I have no idea how to do that within the scope of my knowledge.

    The required output should be:
    Andover
    1 Bed Flat : 75 60 300
    2 Bed Flat : 160 710 45 207
    1 or 2 Bed House : 221 77 65
    3 Bed House : 101 37
    4+ Bed House : 141 250
    Followed by a similar output for Belfast

    I cannot upload the screen shot as it exceeds limits so I will attempt to describe:
    Inspector : NationalRegister
    Attribute Type Value
    allTowns java.util.TreeMap Inspect object
    Inspector : java.util.TreeMap
    Key Type Value
    size int 2
    ["Andover"] Town Inspect object
    ["Belfast"] Town Inspect object
    Inspector : Town
    Attribute Type Value
    townName java.lang.String "Andover"
    bedApps java.util.Map Inspect object
    Inspector : jave.util.HashMap (need the keySet() for this level)
    Key Type Value
    size int 5
    ["1 Bed Flat"] java.util.ArrayList Inspect object
    + 4 others
    Inspector : java.util.HashMap (need the values from this level)
    Position Type Value
    size int 3
    [0] java.lang.Integer 75
    + 2 others

    Hoping that somebody can help
    Whisperer
    Last edited by Whisperer; 08-19-2011 at 07:38 PM. Reason: legibility

  7. #7
    JeffGrigg is offline Member
    Join Date
    Aug 2011
    Posts
    95
    Rep Power
    0

    Default

    Doesn't seem to hard. Seems like you're almost there.

    You might want this to be a 'public static final' variable somewhere (a constant), or maybe a field on Town, as you will be needing it:
    Java Code:
    String[] accomType = { "1 Bed Flat", "2 Bed Flat", "1 or 2 Bed House", "3 Bed House ", "4+ Bed House" };
    In the NationalRegister class, I would recommend using the 'Town' data type / class name in several places where you are currently using 'Object'. Then you can do this:
    Java Code:
    Town town = allTowns.get(townName);
    And at that point, you seem to have access to pretty much all the data you need.

  8. #8
    Whisperer is offline Member
    Join Date
    Aug 2011
    Location
    Cornwall, UK
    Posts
    22
    Rep Power
    0

    Default

    Thanks Jeff for the response, I don't need the public static final because it can vary between towns and, as such, is passed as a variable to 'recordApplications(String[] houseType, Integer[][] appNo)' (houseType) in the Town class.

    Replacing Object and will report back.

  9. #9
    Whisperer is offline Member
    Join Date
    Aug 2011
    Location
    Cornwall, UK
    Posts
    22
    Rep Power
    0

    Default

    I could not get the replacement of the Objects to give me what I want which is the code to allow me to access the information in the last two layers of the Inspectors.

    In my opinion they should involve something.keySet() for the fourth layer and something.values() for the last but what is the 'something' or do I have to loop through each of the preceding 3 levels to get the something, in which case how?
    Whisperer (still )
    Last edited by Whisperer; 08-19-2011 at 05:11 PM.

  10. #10
    JeffGrigg is offline Member
    Join Date
    Aug 2011
    Posts
    95
    Rep Power
    0

    Default

    The answer does involve a few nested loops.

    With just a few changes and additions to your code, I get this output:
    Java Code:
    Andover
    1 Bed Flat: [75, 60, 300]
    2 Bed Flat: [160, 710, 45, 207]
    1 or 2 Bed House: [221, 77, 65]
    3 Bed House : [101, 37]
    4+ Bed House: [141, 250]
    Belfast
    1 Bed Flat: [720, 25, 250]
    2 Bed Flat: [55, 128, 770]
    1 or 2 Bed House: [177, 160, 220]
    3 Bed House : [121]
    4+ Bed House: [270, 77]
    (No. I'm not going to show you the code. I'm evil. And an instructor. )

    (The square brackets are there because I'm kind of lazy: I didn't bother to implement one of the loops that would be needed to really do it right. )

    If you have made progress, it would probably be helpful to post your new up-to-date implementation. I assume that you have more code in the 'NationalRegister.printAllRecords()' method now.

  11. #11
    Whisperer is offline Member
    Join Date
    Aug 2011
    Location
    Cornwall, UK
    Posts
    22
    Rep Power
    0

    Default

    Thanks Jeff,
    I am failry confident with my Town code and if I am wrong then I will be hung for it, but so far this and its predecessor have caused nearly a fortnights anguish, and, at 73 years young, I will not move on until I understand it. As regards the print routine, I have lost track of the code that has been in there and removed, including your suggested changes to Object.
    I am hopeful that something may have just 'cast' a light on my problems - get back later

  12. #12
    Whisperer is offline Member
    Join Date
    Aug 2011
    Location
    Cornwall, UK
    Posts
    22
    Rep Power
    0

    Default

    Wrong yet again! I appreciate that you can not give me the code Jeff, how about some reading matter that will advise me how to extract a HashMap used as a value in a TreeMap pairing? Better still, one that does include an example.

    current print routine is below including some of the trials that failed! Laughing not permitted! At this moment I am still trying to get below the keySet level
    Java Code:
       public void printAllRecords()
       {
          Set<String> towns = allTowns.keySet(); 
          Collection<Town> town = allTowns.values();
    
          //System.out.println(town.size());
          for (String townName : towns)
          { 
             System.out.println(townName);
             {
             /* Tried to cast trial to the object contained in allTowns.get(townName)        
             Town trial = (Town) allTowns.get(townName);
             
             Information gathering*/
            // System.out.println(town.getClass());         
            // System.out.println(allTowns.get(townName));
            // System.out.println(trial.getCentreName());
            /*Trying to access the next level below townName
             this one fails because Town has no keySet
             Set<String> keys = trial.keySet();
             
             The following code will allow me to print the house type and applications
             when I get there!        
                for (String accom : bedApps.keySet())
                {
                   System.out.print(accom + " :" );
                   List<Integer> apps = bedApps.get(accom);
                   String strg = new String();
                   for(int appNo = 0; appNo < apps.size(); appNo++)
                   {
                      strg = ("  " + apps.get(appNo));
                      System.out.print(strg);
                   }
                   System.out.println();
                }
                System.out.println();
    */         }
          }  
       }
    Best wishes
    Whisperer

  13. #13
    JeffGrigg is offline Member
    Join Date
    Aug 2011
    Posts
    95
    Rep Power
    0

    Default

    (I might be saying the same thing several different ways below.)

    ....

    I think that my post above at '08-16-2011 03:08 PM' shows the two most common ways to get from 'allTowns' to a 'String townName' and a Town instance.

    ...

    The declaration of allTowns is 'TreeMap<String, Town>'. The String is the town name. So you have a sorted list of town names (the String values) as keys. And for each "town name" key, you have one 'Town' instance that you can get by using the key.

    ... Hmmm...

    I see this line
    Java Code:
    	         System.out.println(allTowns.get(townName));
    and I add this line right after it:
    Java Code:
    	         System.out.println(allTowns.get(townName).getClass());
    When I run it, this tells me that the class returned from 'allTowns.get(townName)' is... ___________.

    So I could say...
    Java Code:
    	         ThatClassName someVariableName = allTowns.get(townName);
    ...

    Once you get yourself a 'Town' instance... (Like 'Town town = <something>;') It will help to realize that 'bedApps' is a field on Town, not a field on NationalRegister. So if that code is in the NationalRegister class, you'll have to say 'town.bedApps', and make the 'bedApps' field protected or public. (That's an ugly thing to do, but it will work, short term. )

  14. #14
    JeffGrigg is offline Member
    Join Date
    Aug 2011
    Posts
    95
    Rep Power
    0

    Default

    For reading material, most of the links from this Google search are helpful: Google Search: how to use java map <---<<< (click there!) Most of them use HashMap. But the only difference between HashMap and TreeMap is the order of the keys: TreeMap keeps the keys (like town name) in sorted (alphabetical) order, while HashMap... makes a hash of the order.

    I'm going on 50, but I've been doing this since I was in Jr. High school.

    The important thing to understand when working with Maps is "I have a Map who's keys are <ThisThing>. When I use a key to look up a value, I get <ThisOtherThing>." When you have a 'Map<String, Kitty>', you use some String value to get a Kitty. Once you have an instance of a Kitty, you can do... all the things that you would normally be able to do with an instance of a Kitty.

    Generally, in Java 5 and above, if you see 'Object' or casting, then someone's missing something -- like "<Type>" declarations on some collections classes. There are some "edge" cases where casting is still needed, but you don't see them very often.

Similar Threads

  1. Cannot return values from hashmap
    By uhertz in forum New To Java
    Replies: 1
    Last Post: 06-17-2011, 04:16 PM
  2. how to get the values from hashmap
    By baktha.thalapathy in forum New To Java
    Replies: 5
    Last Post: 05-25-2010, 02:12 PM
  3. Replies: 5
    Last Post: 07-28-2009, 10:22 PM
  4. HashMap contains all values but doesn't show all values
    By xcallmejudasx in forum New To Java
    Replies: 3
    Last Post: 05-10-2009, 11:35 PM
  5. how to return values from hashmap
    By oregon in forum New To Java
    Replies: 2
    Last Post: 08-01-2007, 04:56 PM

Tags for this Thread

Posting Permissions

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