Solved

map with string and object

Posted on 2014-02-25
21
357 Views
Last Modified: 2014-05-04
Hi,

I am looking at below link but not very clear

stackoverflow.com/questions/6870973/want-to-create-a-mapstring-object-object-can-be-string-and-can-be-class-obj

CAn you please provide some background why and how to declare or use above map.

can yo please provide complete example on this.

please advise
Any links resources ideas highly appreciated. Thanks in advance
0
Comment
Question by:gudii9
  • 10
  • 9
  • 2
21 Comments
 
LVL 26

Accepted Solution

by:
dpearson earned 450 total points
ID: 39886689
The original poster was using a Map to store 2 different types of values.  Sometimes Strings and sometimes something else (he says Object).

E.g.
Map<String, Object> map = new HashMap<String, Object>();
map.put("key1","Hello") ;
map.put("key2","Goodbye") ;
map.put("key3", new Integer(10)) ; // This is an object that is not of type string
map.put("key4", new ArrayList()) ; // Another object that is not of type string

Then the answer posted lower in the question is how to work with this map, which would look something like this for my example:

Map<String, Object> map = new HashMap<String, Object>();
...
for (Map.Entry<String, Object> entry : map.entrySet()) {
    if (entry.getValue() instanceof String) {
       String value = (String)entry.getValue() ; 
        // Do something with entry.getKey() String value
    } else if (entry.getValue() instanceof List) {
        List value = (List)entry.getValue() ;
        // Do something with entry.getKey() List value
    } else if (entry.getValue() instanceof Integer) {
        Integer value = (Integer)entry.getValue() ;
        // Do something with entry.getKey() Integer value
    } else if (entry.getValue() instanceof Object) {
        Object value = (Object)entry.getValue() ;
        // Do something else with entry.getKey() generic Object
    } else {
        throw new IllegalStateException("Unexpected types in map");
    }
}

Open in new window


You should generally avoid maps like this (where the values are of different types) because it makes the code that works with it more complicated (as you can see above).  But there can be situations where it's appropriate and this is how you'd work with it.

Doug
0
 
LVL 14

Expert Comment

by:CPColin
ID: 39886701
One of the comments on that question says this:

It is not quite clear what you want to achieve.

The asker never clarified. The commenter's point is still valid. What are you trying to use this map for? If you don't have a specific use case, and are just confused about that StackOverflow question, my advice is to forget about it, because, as dpearson says above, it's not a very useful data structure.
0
 
LVL 7

Author Comment

by:gudii9
ID: 39889702
I am creating objects ObjectDef and FieldDef

Then I am creating an example input file ObjectDefs.txt

Then i will create initialization method that reads that files and creates

a map <className, ObjectDefinition>

so that i can look up after that just by the className to get the ObjectDef for it using reflection.

Then I parse the text file and send to one other application/system.

So i am bit not clear how to achieve this in this context. Any good working example around this. Please advise.
0
 
LVL 14

Assisted Solution

by:CPColin
CPColin earned 50 total points
ID: 39889957
Isn't that just a Map<String, ObjectDefinition>?
0
 
LVL 26

Expert Comment

by:dpearson
ID: 39889996
I think CPColin is right it's

Map<String, ObjectDefinition> where String is className

Then you may also want

Map<ObjectDefinition, FieldDef>

if you are keeping a set of fields per object.

So it's two maps, not a single map containing two types of values.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 39893876
These are kind of real time complex scenarios i come across in the projects. But java doc which always give simple arraylist, hash map etc etc examples.

Where i can i find these kind of real time complex project scenarios, examples to practice, to understand better, faster?
Some times for me understanding the requirement is bit challenging and then next step development which is some what manageable with some help?

please advise
0
 
LVL 26

Expert Comment

by:dpearson
ID: 39893934
I don't think there are any real shortcuts.  I think you're doing the right thing, reading a lot, asking a lot of questions, looking at real code.  Not sure what else you can do to learn this stuff.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 39900738
I think you're doing the right thing, reading a lot, asking a lot of questions, looking at real code.  Not sure what else you can do to learn this stuff.

I am learing definitely but not as fast as my new projects want me to. Sometimes they expect me to be be rockstar with the code within no time that is where i need to master these complex collection related things with object holding other object and having different kinds of keys and how to undertasnad write etc. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 39900742
Map<String, ObjectDefinition> where String is className

Then you may also want

Map<ObjectDefinition, FieldDef>

if you are keeping a set of fields per object.

So it's two maps, not a single map containing two types of values.


any compelte code example to explain this concept. Please advise
0
 
LVL 26

Expert Comment

by:dpearson
ID: 39901058
I am creating objects ObjectDef and FieldDef

Then I am creating an example input file ObjectDefs.txt

Then i will create initialization method that reads that files and creates...

How about you post your code first and then we suggest how to modify it, rather than us writing a whole app for you?
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 7

Author Comment

by:gudii9
ID: 39954527
Map<String, ObjectDefinition> where String is className

Then you may also want

Map<ObjectDefinition, FieldDef>

if you are keeping a set of fields per object.

So it's two maps, not a single map containing two types of values.

It is making more sense now.

Looks like we are using one Map as below
Map<String, ObjectDefinition> where String is className

Then on LinkedList as below to read line by line different kind of text files like StockDefinition.txt, GeneralRecordDefinition.txt, TradeApplicationDefinition.txt, ConsumerDefinition.txt etc
List<FieldDef> FieldDefList = new LinkedList<FieldDef>();
not 2nd map as below
Map<ObjectDefinition, FieldDef>

Each line is as below
600,900,Stocksegment,List,Trade,1
900,902,NN_DATE_PPPP_MM,Primitive,String
(where Index start point, end point index,size,name of the field,fieldPrimitive that is defined,Class Name,optional list Count

I wonder what is advantage or practical use of LinkedList compared to map here. Please advise.
0
 
LVL 26

Expert Comment

by:dpearson
ID: 39960843
It looks like they are using a list of fields because the fields have no names.

If you're reading a line like this:

600,900,Stocksegment,List,Trade,1

then you're relying on the position in the list to give it meaning.  So a LinkedList is a reasonable way to represent this.  Element 2 in the list is the "end index" because of its position.

If you had XML or JSON then you'd have a name to go with the value:

<myline start="600" end="900" name="Stocksegment" ...>

and a map would be a more natural representation where the name of the field would be the key in the map.

Hope that all makes sense.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 39976517
then you're relying on the position in the list to give it meaning.  So a LinkedList is a reasonable way to represent this


Can you please elaborate on this. I am not clear on this point
0
 
LVL 26

Expert Comment

by:dpearson
ID: 39977261
If I give you two sets of data:

500, 800, IBM

and

start="500", end="800", company="IBM"

you can see that in some sense they both represent the same data.

But to know that "500" is the start price in the first set, you need to know that the start price comes first in the list.  It relies on the order of that list.

In the second one, the order doesn't matter.
end="800", start="500", company="IBM" is just fine - there's no confusion

So when the order doesn't matter and you have the names, a map makes sense:
<start="500", end="800", company="IBM"/>   <-- use a map

But when the order does matter and you have no names then a list makes sense:
500, 800, IBM    <-- use a list

Is that clear now?

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 39995053
Map<String, Object> map = new HashMap<String, Object>();
...
for (Map.Entry<String, Object> entry : map.entrySet()) {
    if (entry.getValue() instanceof String) {
       String value = (String)entry.getValue() ;
        // Do something with entry.getKey() String value
    } else if (entry.getValue() instanceof List) {

for (Map.Entry<String, Object> entry : map.entrySet()) {

what is meaning of above statement. What does map.entrySet() do
0
 
LVL 26

Expert Comment

by:dpearson
ID: 39995160
What does map.entrySet() do

If you're not familiar with how to look up Javadocs for library methods it's good to learn.  In any case here's the documentation:
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#entrySet()

In simple terms it just returns a set of "Entry" objects, which Entry has both the key and the value from the map.  So for a map like:

"A"->10
"B"->20
"C"->100

The entry set would just be a list of pairs like this:

("A",10), ("B",20), ("C",100)

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 39996584
if (entry.getValue() instanceof String) {


there should be similar method entry.getKey() to return key similar to entry.getValue() to return value right. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 39996587
entrySet
Set<Map.Entry<K,V>> entrySet()
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
Returns:
a set view of the mappings contained in this map

In above explanation why are they talking about Set and Map and entrySet and what is meaning of line
Set<Map.Entry<K,V>> entrySet() esp >> please advise
0
 
LVL 26

Assisted Solution

by:dpearson
dpearson earned 450 total points
ID: 39996915
entry.getKey()

Yes that's right - there is a method to get the Key from an entry and another to get the Value.

Set<Map.Entry<K,V>> entrySet()

The definition of this method can be a bit overwhelming so let's break it down.

First Map.Entry<K,V> is just the formal way to say "an entry" in a map.  So these are the entries we've been talking about.

Then the method returns a Set of those entries - which is just a way to say a collection or list or entries.

So in simpler terms this is the same as:

Collection<Entry> entrySet()

Because the entrySet() method returns a collection of entries, you can go through them all like this:

for (Entry entry : map.entrySet()) {
   // Process each entry
}

but more formally this should be written:
for (Map.Entry<K,V> entry : map.entrySet()) {
}

but it's the same concept.

Does this make sense now?

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 40002387

Then the method returns a Set of those entries - which is just a way to say a collection or list or entries.

So in simpler terms this is the same as:

Collection<Entry> entrySet()


when you say Set is it is a collection Set?
or just bunch of those entries.

Is there is a simple example to understand this? please advise
0
 
LVL 26

Expert Comment

by:dpearson
ID: 40002512
A Set is a specific type of Collection.
A List is another Collection.

A "set" means:
1) The elements have no particular ordering
2) The elements have no duplicates
E.g. a set of colors ("red", "blue", "green")

A "list" means:
1) The elements have a particular ordering
2) The elements can have duplicates
E.g. a list of prime numbers ("2","3","5","7","11")

A collection just means "a group of things" - which is why both sets and lists are collections.

In particular in Java, when you have a collection you can walk through the elements, like this:

Collection<Integer> myCollection ;

// Go through each in turn
for (Integer value : myCollection) {
    System.out.println(value) ;
}

Doug
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now