Is there a way to overload the Map's toString() function?

Hello everyone. I was wondering if its possible to overload the toString() function of the Map datastructure supplied by java.
I looked it up and it says:
public class HashMapextends AbstractMapSo I looked up AbstractMap and it says:
public abstract class AbstractMapextends Objectimplements MapAnd I found a toString() function in the AbstractMap saying:
toString
public String toString() Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object). This implementation creates an empty string buffer, appends a left brace, and iterates over the map's entrySet view, appending the string representation of each map.entry in turn. After appending each entry except the last, the string ", " is appended. Finally a right brace is appended. A string is obtained from the stringbuffer, and returned.
here: http://java.sun.com/j2se/1.3/docs/a...ml#toString()So I did the following:
package parse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.*;
//this class should store all the Messages or "Events" and
//you can access them based on their EntityID key.
public class MessageDB extends HashMap
     //database to hold the information
     //     holds the Alerts/messages
     public static Map<Integer, List<String>> AlertMap;
     //Constructor
     MessageDB()
          AlertMap = new HashMap<Integer, List<String>>();
     public String toString()
          return ( )//not sure what to put here...
     //print, outputs the contents of the hashMap
     public static void print()
        //want to print out the Key and all the Messages
          //associated with that key
          Set keys = AlertMap.keySet();          // The set of keys in the map.
          Iterator keyIter = keys.iterator();
          System.out.println("The map contains the following associations:");
          while (keyIter.hasNext()) {
                Object key = keyIter.next();  // Get the next key.
                Object value = AlertMap.get(key);  // Get the value for that key.
                System.out.println( "EntityID: " + key + "\n"
                              + "Message: " + value + "\n" );
     //overloaded print to print to user screen.
     public static void print(PrintWriter out)
          //want to print out the Key and all the Messages
          //associated with that key
          Set keys = AlertMap.keySet();          // The set of keys in the map.
          Iterator keyIter = keys.iterator();
          out.println("The map contains the following associations:");
          out.flush();
          while (keyIter.hasNext()) {
                Object key = keyIter.next();  // Get the next key.
                Object value = AlertMap.get(key);  // Get the value for that key.
               //out.flush();
               /* out.println( "   (" + key + "," + value + ")" );
               out.flush();*/
               // out.println("------------------\n");
               out.println("EntityID: " + key + "\n"
                              + "Message: " + value + "\n");
               //out.println("------------------\n");
               out.flush();
     void add(Message msg)
          //getting the position of the List by EntityID if avaiable
          List<String> Alert = AlertMap.get(msg.entityID);
          //checking to see if there is a unique Key already in the Map.
          if (Alert == null)
               //if there isnt a key in the map, add a new key, and a new List mapping
               //to the key EntityID;
                 Alert = new ArrayList<String>();
                 AlertMap.put(msg.entityID, Alert);
                 Alert.add(msg.message);
          else
          //adding message to List
               Alert.add(msg.message);
}Right now the output is like this:
The map contains the following associations:
EntityID: 99999
                  Message: [a test ]
EntityID: 800
                Message: [this is a test , again a test ]
EntityID: 801
                Message: [again a test ]
EntityID: 111
                Message: [a test again yes , a test once again ]You see how its automatically doing [message1, message2,...,message x]
By me calling this line of code:
out.println("EntityID: " + key + "\n"
                              + "Message: " + value + "\n");Because I found out it implicity calls the toString() method when concatinating it to a string.
What I would like it to display would be:
EntityID: 800
Message:
This is a test
This is a test again
any ideas would be great!
Or is there a way to just iterate over the messages, rather than doing it my way?
Message was edited by:
lokie

Hi,
When you do a String concatenation in java, calls are implicitly done to #toString().
Means, you are doing this:
while (keyIter.hasNext()) {
                Object key = keyIter.next();  /
                Object value = AlertMap.get(key); 
                System.out.println( "EntityID: " + key.toString()+ "\n"
                              + "Message: " + value.toString() + "\n" );
}The "[ [/b]... [b], ... , ... ]" you can see in your output is created by the implicit call to List#toString() method.
You can Override it in an anonymous class by doing:
if (Alert == null)
               //if there isnt a key in the map, add a new key, and a new List mapping
               //to the key EntityID;
                 Alert = new ArrayList<String>(){
                          @Override
                           public String toString(){
                            StringBuilder sb = new StringBuilder();
                   for(String s: this){
                    sb.append(s);
                    sb.append("\n");
                           return sb.toString();
                         };PS:
toString() is usually used for debbuging only...

Similar Messages

  • Is there a way to use the preview in browser function without an Internet connection?

    This morning our cable modem was down and I was making some changes to a page in a Muse site I'm designing. I wanted to preview the changes in a browser, but when I clicked on the Preview button (or clicked on preview in browser), I received a notification that it was checking for an Internet connection and the preview page never completed. Is there a way to use the preview in browser function in Muse without an Internet connection?

    Thanks for getting back to me! When our cable modem went down, we were still connected to Airport Base Station, and perhaps it appeared to Muse that we did have an Internet connection. In any case, we have now received a new cable modem and our network is working again. As you suggested, I disconnected from the network and tried preview in Muse again, and now it seems to be working just fine. Perhaps it was just the circumstances of our network problem this morning. Good to know I can use the Muse Preview function off-line!

  • Is there a way to swap the Fn key and left Ctrl key

    Is there a way to swap the functions of Fn key and left Ctrl key on the keyboard. I'm used to other keyboards where the keys are switched and I keep pressing Fn when I want to press Ctrl.  I figure I'll get used to it eventually, but when I use the laptop in a docking station with a regular keyboard the control key is in one spot and undocked with the Lenovo keyboard the function key is there instead, which makes it hard to get used to.
    If not is there a way to disable the Fn + Space bar function that changes the screen resolution. The programs I use use control + space heavily and my screen resolution keeps changing when I don't want it to.
    It's a small thing I know, but very maddening.

    Thanks, I took the survey. It's interesting the questions on there were asking about location of keys like page up and page down. I find the position of those keys are not that important to me because I don't use them that much and don't seem to mind looking at the keyboard to find them. Also they are almost always in different spots depending on whether you are on a desktop or laptop keyboard so I guess I'm used to unconsciously switching depending on which keyboard I'm on.
    But the left control key is one of the most heavily used, at least by developers like me (control+c to copy, control+v to paste, and control+space for code assist, shift + control + f to format code, shift + control + r to find resources, etc...). I have to hit that Ctrl button 1000 times a day. And the key is in the bottom far left corner on every keyboard (desk top and laptop) I've ever seen until now. Having to remember to look down at the keyboard to find the key is proving difficult and I think is actually hurting my productivity. Especially control+space (when you are expecting a popup to automatically complete the line of code you're working on and instead the screen blinks, resizes and your whole editor loses focus it really breaks your flow of thought, so thanks a million for helping me turn off the silly screen zoom feature).
    Hopefully I'll get used to it like with the other keys like page up and page down although I've had the laptop for two weeks and it's proving difficult. If I had know that Thinkpads have this layout and how maddening it would be to get used to it I probably wouldn't have bought it, even though everything else about it is great. It's amazing how such a small thing can become such an irritant.
    Well thanks again, and if anybody from Lenovo engineering is reading this post, my vote is for some bios setting on the T61P that swaps the functions of Fn and Left control key. It would save me a lot of grief anyway.

  • Is there any way to retreive the FileName in the mapping

    Is there any way to retreive the FileName and so that I can use that in my mapping. This is FILE2RFC scenario with NO BPM.
       I am using the adapter specific message attributes in the file sender CC.
    Thanks,
    Ravi
    null

    Yes you can retreive it.  Create an simple user defined function in the mapping and use the following code.
    Imports: com.sap.aii.mapping.api.*;
    Parameter: String filename
    Paramter: String filename;
    filename = fileName + ".DAT";
    DynamicConfiguration conf = (DynamicConfiguration) container
    .getTransformationParameters()
    .get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
    DynamicConfigurationKey key = DynamicConfigurationKey.create( "http://sap.com/xi/XI/System/File", "FileName");
    conf.put(key, filename);
    return filename;
    Or
    Just do whatever mentioned in this weblog:
    /people/michal.krawczyk2/blog/2005/11/10/xi-the-same-filename-from-a-sender-to-a-receiver-file-adapter--sp14
    ---Satish

  • Is there any way to reinstall google maps as the new map app is at best dire

    Since the latest iOS 6 to say the maps application is dire would be an understatment, My house no longer exists and a new street has appeard behind where i live , i used to use the application all the time as im a mobile mechanic and need a reliable navigation system ,( now reduced to having to return home to print out directions ) i do know that you can use google maps if you connect to the internet but sometimes this is not possable in my are . is there a fix or can we please have google maps back also NO STEET view    REALLY  im begining to wonder if i should bother with the new 5 or just get a SAMSUNG

    Satellite A505-S6005
    I have reinstalled the utilities and drivers by using the recovery disks I made when the laptop was new, but have since lost them.  I only want to reinstall a few utilities and drivers, but not restore the whole system.  Is there any way to reinstall the "Toshiba Application Installer" or recreate the recovery disks?
    Most may be downloaded from here.
    You should be able to burn recovery discs. See the section Creating recovery DVDs/media, which begins on p. 69 of the User's Guide.
       Satellite A500 Series User’s Guide
    If that doesn't work, you can obtain them from Toshiba.
       Order Toshiba Recovery Media
    -Jerry

  • Is there any way to keep the old maps app?

    I'd upgrade, but maps the way it is now works very well for me and is one of the things I use most on my iPhone. Is there any way to keep the old version of maps when upgrading?

    No - just don't upgrade until Google release there maps app.  I wish I could go back to yesterday and give myself this advice.

  • Is there a way to create multiple map tile layers at once?

    Hello experts,
    I have a small problem. It's mainly a matter of saving some time. I need to create 51 map tile layers in mapviewer, and I would like to this this at one time. I can go to the admin console-->Management-->Manage Map Tile Layers-->Create, and then I can create one at a time. But it really would be nice to create them all at once!
    I tried using the XML mode interface, and I can use the following code to create one map tile layer:
    <?xml version="1.0" standalone="yes"?>
    <map_tile_server_admin_request>
      <create_map_tile_layer data_source="xxxx">
        <map_tile_layer
            name="FOUNDATION"
            http_header_expires="168"
            image_format="PNG">
          <internal_map_source base_map="FOUNDATION"/>
          <tile_storage root_path="/scratch/tilecache" />
          <coordinate_system
              srid="8265"
              minX="-180" maxX="180" minY="-90" maxY="90"/>
          <tile_image width="250" height="250" />
          <zoom_levels levels="10" min_scale="5000" max_scale="10000000">
          </zoom_levels>
        </map_tile_layer>
      </create_map_tile_layer>
    </map_tile_server_admin_request> And it creates one layer. But when I try this:
    <?xml version="1.0" standalone="yes"?>
    <map_tile_server_admin_request>
      <create_map_tile_layer data_source="xxxx">
        <map_tile_layer
            name="FOUNDATION"
            http_header_expires="168"
            image_format="PNG">
          <internal_map_source base_map="FOUNDATION"/>
          <tile_storage root_path="/scratch/tilecache" />
          <coordinate_system
              srid="8265"
              minX="-180" maxX="180" minY="-90" maxY="90"/>
          <tile_image width="250" height="250" />
          <zoom_levels levels="10" min_scale="5000" max_scale="10000000">
          </zoom_levels>
        </map_tile_layer>
      </create_map_tile_layer>
      <create_map_tile_layer data_source="xxxx">
        <map_tile_layer
            name="FOUNDATION_WY"
            http_header_expires="168"
            image_format="PNG">
          <internal_map_source base_map="FOUNDATION_WY"/>
          <tile_storage root_path="/scratch/tilecache" />
          <coordinate_system
              srid="8265"
              minX="-180" maxX="180" minY="-90" maxY="90"/>
          <tile_image width="250" height="250" />
          <zoom_levels levels="10" min_scale="5000" max_scale="10000000">
          </zoom_levels>
        </map_tile_layer>
      </create_map_tile_layer>
    </map_tile_server_admin_request>...it creates only the first map tile layer in my xml request.
    Is there any way to create multiple map tile layers at once?
    Thank you!
    John

    Michael,
    It looks like you are right! Thank you for your help.
    I still have a small concern. I looked at the documentation and it reads,
    "The configuration settings for a cache instance are stored in the USER_SDO_CACHED_MAPS metadata view. You should normally not manipulate this view directly, but should instead use the MapViewer administration tool, which uses this view to configure map cache instances."
    But, I tried inserting records into USER_SDO_CACHED_MAPS and it works, and I can't really see any reason not to directly insert records into this table, so...
    Perhaps that warning is there simply because potentially you could screw things up tinkering with the table directly.
    Cheers!
    John

  • Is there a way to force the Tag Engine to dump its input buffer to the database?

    I have an application where I start a process and log the data, and then call a subVI that uses the Read Historical Trend VIs to get all of the data from when the process started until now. The problem is that the Historical Trend VIs only read from the database on disk, and the Tag Engine's buffer doesn't write to disk until it's full (or possibly times out; I'm not sure about that, though). Is there a way to force the Tag Engine to write to disk, so that the Historical Trend VIs will return the most recent data?
    Shrinking the buffer will help a little, but that will only result in missing less of the most recent data. One possible hack is to have a dummy tag that I simply write enou
    gh data to that will cause the buffer to be written to the database. I was hoping for something more elegant, though.

    That's a good question.
    The control about the datalogging and the DSC Engine is all done (more or less) automatically - you feel the NI ease-of-use idea
    That means the Citadel service (one of the NI Services installed by LabVIEW DSC) is responsible of taking care about the datahandling (writing to and reading from the database files including caching some data e.g. index files, frequently used data...).
    The DSC Engine makes a request to the Citadel service that this data has to be logged. Everything else is handled by the Citadel service. Internally, there are two kinds of logging periods handled through the Citadel service. One for traces being viewed (a small period: 200ms) and one for traces not being viewed (slow (big) log period: 20000ms). That
    means, if Citadel gets a request to store a value it will buffer it and store it as soon as possible depending on other circumstances. One depends on the fact if this trace data is being viewed (e.g. with Read Histroical Trend.vi) If you request/read to view a trace you should pretty much see the current values because citadel should use the fast log period.
    The Citadel service takes care as well about setting priorities e.g. the writes before the reads (We don't want to loose data - right?). That means if you really stuff the system by writing a lot of data the CPU might get overloaded and the reads will happen less often.
    If you really want to see "real-time" data I would recommend to use the "Trend Tags.vi". With this approach you avoid the chain DSCEngine-Output Buffer-CitadelService-InputBuffer-File-HD... and back.
    I hope this info helps.
    Roland
    PS: I've attached a simple VI that has a tip (workaround) in it which might do what you are looking for... However, Nationa
    l Instruments cannot support this offically because the VI being used are internally DSC VIs that certainly change in the next version of LV DSC... and therefore you would need to "re-factor" your application.
    Attachments:
    BenchReadHistTrend.llb ‏104 KB

  • Is there a way to make the NAS200 act like a drive in my computer

    Not sure if this has been discussed here yet.
    I have a NAS200 connected to my router and I can access through my web browser no problem.
    I was wondering if there's a way to make it act like a drive that's in my computer. i.e give it a drive letter and have it show up in the "my computer" area.
    I am running win 8 pro desktop hard wired to the router with the nas200 connected. Is there a way to "mount" the nas200 as drive on the computer.
    Thanks,
    Bob
    Solved!
    Go to Solution.

    Yes, you just need to map the drive on your computer. You need to make sure first that the network drive is detected in the network. You can click on the following link to know how to map the drive:
    How to create a shortcut to map a network drive

  • Is there a way to get the actual XML string when using the JAXP SAX Parser?

    Hi All,
    I am using a JAXP SAX xml parser and am looking for a way to get the actual line of xml that is being parsed from within a content handler.
    Here's my scenario. Consider the following example xml document.
    <formCollection>
       <form name="myForm">
          <text/>
          <selection/>
       </form>
       <form name="anotherForm">
          <text/>
       </form>
    </formCollection>My hope is to validate the entire document and then insert an xml string containing each "form" element (and its sub-elements) into a map for later use. My thought was to create a String as each "form" element is being parsed (begining with the form's startElement event and concatenating until the form's endElement event is reached) and then inserting this string into the map. Is there a way to get the actual line of xml that is being parsed, rather than just the element name and attribute values?

    DrClap wrote:
    YouRang wrote:
    2. The first handler would validate the entire XML document, extract the "type" attribute from each <form> element, and place each <form> element and its sub-elements into the map of Strings, using the "type" attribute as the key. The second handler would take a <form> element and parse it into a Form object for the display. This option was the impetus for my question because it relies on the first handler being able to access the entire <form> element XML String and write it to a map.I don't see why you need the raw data from the XML document here. You should already be abstracting your data into Java classes in the first handler, instead of making the second handler do the parsing all over again.Correct, I am not referring to XForms. In this case, it happens that I am using the XML to generate an SWT ScrolledForm object and, thus, the XML element name happens to be named "form." However, the concept/design problem could apply to any type of object and the XML element could be appropriately renamed.
    My experience with XSLT is limited and I haven't done anything with it for several years. With that said, it seems that it is primarily used for generating web content, which wouldn't apply in this case because this is for a client-server application. I could be off base on this one -- if XSLT applies to much broader translations and would be more appropriate for generating Java objects than my current methodology, I could certainly look into it further.
    I apologize that option two didn't make more sense; it is difficult to explain. Yes, optimally the data should be abstracted into Java classes in the first handler. This is really an elaboration that I failed to specify when explaining option one. The problem is that the user can choose to create any number of "forms" of any type. For instance, let's say that from the File -> New menu there are options for seven different types of forms and each form is used to send completely different data. The user can select form1, select form1 again, select form4, and select form7 (or any other combination) and bring up tabs that display the different forms. The user can then enter data and submit each form separately. When the user selects File -> New -> FormX, a SWT ScrolledForm object that corresponds with FormX must be given to the display. Because SWT ScrolledForm objects do not allow a deep copy, I cannot simply read the XML <form> elements at initialization, parse them into ScrolledForm objects, and pass deep copies of the ScrolledForm objects to the display each time the user clicks File -> New -> FormX. The only simple way I see of getting a new copy of a ScrolledForm object is to reparse the appropriate XML <form> element in order to create one each time the user selects File -> New -> FormX. As such, one handler would need to read the entire XML document and parse the <form> elements into a map (or some other data structure) and another handler would need to parse individual <form> elements into SWT ScrolledForm objects. The first handler would be called at initialization and the second handler would be called each time a user clicked on File -> New -> FormX. Once again, this isn't exactly my favorite implementation... but seems the simplest given that there is no way to do a deep copy of an SWT ScrolledForm object. Hopefully that makes a little more sense. No worries if it doesn't -- I just figured I'd throw this out there and see if anyone had a better idea.

  • Does any one know is there a way to take off maps and passbook off  your phone

    Does any one know, is there a way to take off maps and passbook app off your Iphone ?

    I have just put them on last window, out of the way- useless.

  • Is there a way to know the qualifier or qualifers that were applied

    Hi All,
    If I have a promotion like this Buy2 get 2 is there a way to know the qualifier or qualifiers that were applied?
    I will end up by having 4 commerce Items and two will be free with an adjustment of the promotion that was applied, but I do not know which items were the ones that make that possible
    is there a way to know that?
    Which items were used to get a BOGO or BuyXGetY?
    Regards,
    Obed

    Hi All,
    If someone needs to know this in the future
    findQualifyingItems() is the one in charge of knowing which items had promotions and it calls a method called evaluateQualifier wihch "can" contain a List of items that are the ones that were used to apply a promotion like BOGO or BuyXGetY.
    Basically the solution for me was override QualifierService and
    @Override
         public Collection findQualifyingItems(PricingContext pPricingContext,
                   Map pExtraParametersMap)
    In order to save the info in a Map I am using CommerceItemMarkers http://docs.oracle.com/cd/E35318_02/Platform.10-1-1/ATGCommStoreGuide/html/s1401usingorderandcommerceitemmarkers01.html
    And now I have my business requirement covered thanks to this.
    Regards,
    Obed
    Edited by: obedmhg on May 17, 2013 2:53 PM

  • Is there any way to prioritize the Messages in ALSB?

    Hi all,
    Is there any way to prioritize the messages based on some property of the message in ALSB. For example the messages from a specific sender is to have higher priorty.

    You can configure thread pools on your different proxy/business service (dispatch policy). Therefore prioritizing client requests based on the service invoked.
    In ALSB 3.0 you will also be able to control service throughput, for example you don't want to overload your back-end system with requests from ALSB.
    Gregory Haardt
    ALSB Prg. Manager
    [email protected]

  • Hi. I have a new ipad air. Is there a way to enlarge the clock font? All other fonts are fine. Thanks.

    Hi. I have a new ipad air. Is there a way of enlarging the clock font? All other fonts are ok. Thanks.

    You can download a complete iPad 2 User Guide here: http://manuals.info.apple.com/en/ipad_user_guide.pdf
    Also, Good Instructions http://www.tcgeeks.com/how-to-use-ipad-2/
    Apple - iPad 2 - Guided Tours
    http://www.apple.com/ipad/videos/
    Watch the videos see all the amazing iPad apps in action. Learn how to use FaceTime, Mail, Safari, Videos, Maps, iBooks, App Store, and more.
    You can download this guide to your iPad.
    iPad User Guide for iOS 5
    http://itunes.apple.com/us/book/ipad-user-guide-for-ios-5/id470308101?mt=11
     Cheers, Tom

  • Is there a way to display the coordinates(x,y)  of the objects automatically ?

    hi and happy new year
    is there a way to display the coordinates(x,y)  of the objects automatically (may be on a label over the object ) and print them?
    i mean i want to design a game level (in pixels) place the object on the map ang get the locations automatically to print them
    thank you
    txarly

    Good day!
    Which version of Photoshop do you use?
    If you have CS6 Etended the Measurement Log might provide some options to store and print the information separately, but if I interpret your wuestion correctly (for example that by »object« you mean »Layer«) I think a Scripting approach would be best.
    Scripts can be used to automate tasks with more options regarding conditionality than Actions by using JavaScript-, VB- or ApplaScript-code to control Photoshop.
    If you want to pursue that option you could ask for help over at
    http://forums.adobe.com/community/photoshop/photoshop_scripting
    or
    http://ps-scripts.com/bb/
    But please post screenshots/mock-ups right away to illustrate what you start with and what result you want.
    Regards,
    Pfaffenbichler

Maybe you are looking for