I have two dictionaries added into parent dictionary. How to retrieve data from a value (which is a dictionary)
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int count =2;
Dictionary parent_dic = new Hashtable();
Dictionary child1 = new Hashtable();
Dictionary child2 = new Hashtable();
Dictionary child = new Hashtable();
child1.put("1", "one");
child1.put("2", "two");
System.out.println("Child1" + child1);
child2.put("3", "three");
child2.put("4", "four");
System.out.println("Child2" + child2);
for(int each_c = 1; each_c <= count; each_c++) {
if(each_c==1) {
child = child1;
} else {
child = child2;
}
parent_dic.put(each_c,child);
}
System.out.println("Parent" + parent_dic);
System.out.println("test ::: " + parent_dic.get(1));
}
}
How to get value from resultant value (which is dictionary)?
Output:
Child1{2=two, 1=one}
Child2{4=four, 3=three}
Parent{2={4=four, 3=three}, 1={2=two, 1=one}}
test ::: {2=two, 1=one}
How to get value "two" from above test dictionary.
I tried to rewrite your code in a way that made more sense to me.
I've added the use of proper types as well, using raw types in java is dangerous. The last line of my code does what I believe you want. Note the difference between using Integers as keys and Strings as keys.
public static void main(String[] args) {
Dictionary<Integer, Dictionary> parent_dic = new Hashtable();
Dictionary<String, String> child1 = new Hashtable();
Dictionary<String, String> child2 = new Hashtable();
child1.put("1", "one");
child1.put("2", "two");
System.out.println("Child1" + child1);
child2.put("3", "three");
child2.put("4", "four");
System.out.println("Child2" + child2);
parent_dic.put(1, child1);
parent_dic.put(2, child2);
System.out.println("Parent" + parent_dic);
System.out.println("test : " + parent_dic.get(1));
System.out.println("two : " + parent_dic.get(1).get("2"));
}
You need to add generic types to your variable declarations (e.g. Dictionary<Integer, Dictionary> parent_dic = new HashTable<Integer, Dictionary>();)
Without them the compiler tries to add them in, not always successfully. The key and value pairs for your parent_dic, child1, and child2 have defaulted to Object. You can add anything to them, even a Random object or an ArrayList. If you try to access the output of your last line by adding .get("1") it won't compile, because you are trying to use get("1") on an Object.
If you add the types, like Dictionary<Integer, Dictionary> you can access the data in the child dictionaries.
Related
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Maps {
public static void main(String[] args) {
Map mapA = new HashMap();
Map mapB = new TreeMap();
mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");
// The three put() calls maps a string value to a string key. You can then
// obtain the value using the key. To do that you use the get() method like this:
String element1 = (String) mapA.get("key1");
// why do I need the type cast on the right?
System.out.println(element1);
//Another examples with maps
Map vehicles = new HashMap();
vehicles.put("BMW", 5);
vehicles.put("Mercedes", 3);
vehicles.put("Audi", 4);
vehicles.put("Ford", 10);
System.out.println("Total vehicles: " + vehicles.size());
for(String key: vehicles.keySet())
System.out.println(key + " - " + vehicles.get(key));
System.out.println();
String searchKey = "Audi";
if (vehicles.containsKey(searchKey))
System.out.println("Found total " + vehicles.get(searchKey) + " "
+ searchKey + " cars!\n");
// clears vehicles
vehicles.clear();
//should equal to 0 now
System.out.println("Vehicle now contains this many vehicles :" + vehicles.size());
// Lets iterate through the keys of this map:
Iterator iterator = mapA.keySet().iterator();
System.out.println(iterator); // How to inspect this? Is it a kind of map?
Map mapC = new HashMap();
while(iterator.hasNext()){
Object key = iterator.next();
Object value = mapA.get(key);
mapC.put(key,value);
} // Is there a better way to take the contents of the iterator and put them in a new map?
System.out.println(mapC);
//create a new hashmap
HashMap hm = new HashMap();
// put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));
//get a set of the entries
// The entrySet( ) method declared by the Map interface returns a Set containing the
// map entries.
Set set = hm.entrySet();
// get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.println(i.getClass()); // get the class of i
System.out.println(i instanceof Iterator); // checks to see if i is of class Iterator
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double)hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " +
hm.get("Zara"));
}
}
This is my error:
Maps.java:53: error: incompatible types: Object cannot be converted to
String
for(String key: vehicles.keySet())
My questions are
Why is that error occurring? Why is an object trying to be converted to a string? I thought I had put strings as keys into the vehicles HashMap. What is going on?
Why is the typecast needed in the line:
String element1 = (String) mapA.get("key1");
vehicles.keySet() returns a collection of Object, not String. Just because you put strings in as the keys, the API doesn't change.
One approach would be:
for(Object keyObj: vehicles.keySet())
{
String key = keyObj.toString(); // or cast to (String)
Same issue - get() returns an Object. Just because you used a string, the API is still just an object. Again either cast or use toString.
As has been hinted in various comments, if you use generics the compiler has a much better idea of "what types are where". If you define your map like Map<String,String> mapA = new HashMap<String, String>(); then your original code may work because the compiler knows what the data types in the map are.
I want to access the value in hashtable but in my code there is a exception . I want to access the constructor values of another class within the (KEY,VALUE) in the hastable this is the code of my class
public class StudentReg {
public String RegNo,Program ,FName;
StudentReg(int Roll , String Program, String FName)
{
this.RegNo = " Fall2k14_ " + Roll + " " + Program;
this.FName = FName;
this.Program = Program;
}
And Now i I have used a hashtable in which i want to access the values of the hastable using iterator this is the code of my main class And I have created a object T of hashtable and entered the key and the value set and get the values in the iterator
public static void main(String[] args){
Hashtable T = new Hashtable();
T.put("Ahmed", new StudentReg(123,"BS(CS)","Murtaza"));
T.put("Fahad", new StudentReg(456,"BE(EE)","...."));
T.put("Alan", new StudentReg(769,"BBA","Rashee"));
Set set =T.keySet(); // get set-view of keys
// get iterator
Iterator itr = set.iterator();
while(itr.hasNext()) {
StudentReg S3 = (StudentReg) itr.next();
System.out.println(S3 + ": " +T.get(S3.RegNo+""+S3.Program+""+S3.FName));
}
At this point System.out.println(S3 + ": " +T.get(S3.RegNo+""+S3.Program+""+S3.FName)); i want to access the values which has been passed in the constructor of StudentReg();
but i am unable to do that
You are iterating on your keys which are Strings. If you want to iterate on all objects that are of the StudentReg class, you want to iterate on values().
I strongly recommend to add type parameters to the collections. This way your code would not compile, and you would see right away what the problem is.
Hashtable<String, StudentReg> T
= new Hashtable<String, StudentReg>();
or if using java 7 or newer
Hashtable<String, StudentReg> T = new Hashtable<>();
Then you can iterate on the values() using a foreach construct.
for (StudentReg s : T.values()) {
System.out.println(T.RegNo + " " + T.Program + " " + T.FName));
}
You are trying to cast the String... the keyset returns all the keys, not values...
If you want the keys and values you can do like this:
public static void main(String[] args) {
Hashtable<String, String> hashtable = new Hashtable<String, String>();
hashtable.put("a", "1");
hashtable.put("b", "2");
for (Entry<String, String> tuple : hashtable.entrySet()) {
System.out.println(tuple.getKey(), tuple.getValue());
}
}
I have set up a test that:
retrieves data concerning several court cases: each court case is stored in a CourtCase object
a set of CourtCase objects is then stored in a Map
I retrieve these data twice (from two different sources) so I end up with two Maps
The data within the objects should be the same between the Maps, but the order of the objects within the Maps may not be:
Map1:
A, case1 - B, case2 - C, case3
Map2:
B, case2 - A, case1 - C, case3
How can I best compare these two Maps?
Map#equals does not care about the order. As long as your 2 maps contain the same mapping it will return true.
Map#equals uses Set#equals method, applied to the entry set. Set#equals contract:
Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set).
Note: this assumes that your CourtCase objects have proper equals and hashcode methods to be compared.
Map implementations provides an equals method which do the trick. Map.equals
#user973718 the best to compare two map objects in java is - you can add the keys of a map to list and with those 2 lists you can use the methods retainAll() and removeAll() and add them to another common keys list and different keys list. Using the keys of the common list and different list you can iterate through map, using equals you can compare the maps.
The below code gives this output :
Before {b=2, c=3, a=1}
After {c=333, a=1}
Unequal: Before- 3 After- 333
Equal: Before- 1 After- 1
Values present only in before map: 2
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
public class Demo
{
public static void main(String[] args)
{
Map<String, String> beforeMap = new HashMap<String, String>();
beforeMap.put("a", "1");
beforeMap.put("b", "2");
beforeMap.put("c", "3");
Map<String, String> afterMap = new HashMap<String, String>();
afterMap.put("a", "1");
afterMap.put("c", "333");
System.out.println("Before "+beforeMap);
System.out.println("After "+afterMap);
List<String> beforeList = getAllKeys(beforeMap);
List<String> afterList = getAllKeys(afterMap);
List<String> commonList1 = beforeList;
List<String> commonList2 = afterList;
List<String> diffList1 = getAllKeys(beforeMap);
List<String> diffList2 = getAllKeys(afterMap);
commonList1.retainAll(afterList);
commonList2.retainAll(beforeList);
diffList1.removeAll(commonList1);
diffList2.removeAll(commonList2);
if(commonList1!=null & commonList2!=null) // athough both the size are same
{
for (int i = 0; i < commonList1.size(); i++)
{
if ((beforeMap.get(commonList1.get(i))).equals(afterMap.get(commonList1.get(i))))
{
System.out.println("Equal: Before- "+ beforeMap.get(commonList1.get(i))+" After- "+afterMap.get(commonList1.get(i)));
}
else
{
System.out.println("Unequal: Before- "+ beforeMap.get(commonList1.get(i))+" After- "+afterMap.get(commonList1.get(i)));
}
}
}
if (CollectionUtils.isNotEmpty(diffList1))
{
for (int i = 0; i < diffList1.size(); i++)
{
System.out.println("Values present only in before map: "+beforeMap.get(diffList1.get(i)));
}
}
if (CollectionUtils.isNotEmpty(diffList2))
{
for (int i = 0; i < diffList2.size(); i++)
{
System.out.println("Values present only in after map: "+afterMap.get(diffList2.get(i)));
}
}
}
/**getAllKeys API adds the keys of the map to a list */
private static List<String> getAllKeys(Map<String, String> map1)
{
List<String> key = new ArrayList<String>();
if (map1 != null)
{
Iterator<String> mapIterator = map1.keySet().iterator();
while (mapIterator.hasNext())
{
key.add(mapIterator.next());
}
}
return key;
}
}
I am getting this strange output in HashMap.
I have two ArrayList<String> one containing the key and another containing value.
My HashMap<String,String> will store only string as key and value pair. But key itself is getting stored in value. I have checked my value arraylist, it's printing the value. But during putting it's setting it as key itself.
Code snippet is:
public HashMap<String,String> getLstBarring()
{
ArrayList<String> temparrLst=setPreParameters(fetchPreDetails, 1);
System.out.println("KEY" + temparrLst);
ArrayList<String> tempArrLstId=setPreParameters(fetchPreDetails, 14);
System.out.println("VALUE" +tempArrLstId);
int length=tempArrLstId.size();
for(int index=0;index<length;index++)
{
System.out.println("VALUE IN KEY" + temparrLst.get(index));
System.out.println("VALUE IN VALUE" + tempArrLstId.get(index));
this.lstBarring.put(temparrLst.get(index), tempArrLstId.get(index));
}
System.out.println("INSIDE ODB....>>>>>>>>>>>>>>" + lstBarring);
return this.lstBarring;
}
Problem is:
1st SOP is KEY-printing all the key correctly.
2nd SOP is VALUE-printing all the value correctly.
3rd SOP is VALUE IN KEY----printing all the values.
4th SOP is VALUE IN VALUE--printing all the values.
Hence after ever iteration I am getting value,value in HashMap whereas it should be key,value.
Here's look at my Method:-
public ArrayList<String> setPreParameters(HashMap<Integer,String> fetchPreDetails,int index)
{
switch(index)
{
case 1:
{
arrLstData.clear();
splittedString=fetchPreDetails.get(1).split(",");
Collections.addAll(arrLstData, splittedString);
break;
}
return arrLstData;
Please guide me as to where am I going wrong.
My guess is that either fetchPreDetails is a collection being mutated by setPreParameters() or else setPreParameters() is mutating some other shared state so that the collection referenced by your temparrLst is being changed on the second call to setPreParameters(). I.e.
List<String> strings = new ArrayList();
strings.add("a");
strings.add("b");
List<String> otherStrings = strings;
otherStrings.add("c");
I expect your code assumes that strings would contain "a" and "b" and that otherStrings would contain "a", "b", and "c". This isn't how object references work in Java. The line List<String> otherStrings = strings; makes both strings and otherStrings point to the same collection, and thus changes made using either name affect the same thing.
Edit: Your newly-posted code seems to prove my hypothesis. You have a variable called arrLstData that you clear, populate, and return on each call to setPreParameters(). You're returning the same collection every time you call this method. Therefore you just have multiple handles to the same collection instead of multiple collections. You need to create a new collection and return it each time you call setPreParameters().
Edit again: Maybe this will make it clearer. Here's what you're doing:
public static void main(String[] args) {
Foo f = new Foo();
List<String> list1 = f.getList("a", "b");
System.out.println(list1);
List<String> list2 = f.getList("c", "d");
System.out.println(list2);
System.out.println(list1);
}
static class Foo {
private List<String> myList = new ArrayList<String>();
public List<String> getList(String... strings) {
myList.clear();
myList.addAll(Arrays.asList(strings));
return myList;
}
}
Note that this exhibits exactly the behavior that you're describing, and the correct way to solve it is something like this:
public static void main(String[] args) {
Foo f = new Foo();
List<String> list1 = f.getList("a", "b");
System.out.println(list1);
List<String> list2 = f.getList("c", "d");
System.out.println(list2);
System.out.println(list1);
}
static class Foo {
public List<String> getList(String... strings) {
List<String> result = new ArrayList<String>();
result.addAll(Arrays.asList(strings));
return result;
}
}
You are reusing the same List over and over at your setPreParameters Method.
The List in arrLstData is returned and stored in temparrLst, now you are clearing the the Lists content, putting new stuff in it and storing it to tempArrLstId.
Now the three variables all contain the very same list (they are not equals, its the same!).
There is only one List object at the whole example!
Its like you got a box and label it "A" on one side put stuff in it, label it "B" on another side and wondering why the box "B" is empty when you turn box "A" upside-down.
Did you maybe mean something like this?
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GlobalsMess {
private Map<String, String> lstBarring = new HashMap<String, String>();
private Map<Integer, String> fetchPreDetails = new HashMap<Integer, String>();
public GlobalsMess() {
fetchPreDetails.put(1, "john,vikam,david");
fetchPreDetails.put(14, "1,2,3");
}
public Map<String, String> getLstBarring() {
List<String> tempKeys = setPreParameters(fetchPreDetails.get(1));
System.out.println("KEY" + tempKeys);
List<String> tempIds = setPreParameters(fetchPreDetails.get(14));
System.out.println("VALUE" + tempIds);
for (int index = 0; index < tempIds.size(); index++) {
System.out.println("VALUE IN KEY" + tempKeys.get(index));
System.out.println("VALUE IN VALUE" + tempIds.get(index));
this.lstBarring.put(tempKeys.get(index), tempIds.get(index));
}
System.out.println("INSIDE ODB....>>>>>>>>>>>>>>" + lstBarring);
return this.lstBarring;
}
public List<String> setPreParameters(String fetchPreDetailsValue) {
List<String> arrLstData = new ArrayList<String>();
Collections.addAll(arrLstData, fetchPreDetailsValue.split(","));
return arrLstData;
}
public static void main(String[] args) {
new GlobalsMess().getLstBarring();
}
}
Output:
KEY[john, vikam, david]
VALUE[1, 2, 3]
VALUE IN KEYjohn
VALUE IN VALUE1
VALUE IN KEYvikam
VALUE IN VALUE2
VALUE IN KEYdavid
VALUE IN VALUE3
INSIDE ODB....>>>>>>>>>>>>>>{david=3, vikam=2, john=1}
I am a java newbie, and having some issue with "java.util.List".Below is my code,where I'm trying to create a list of objects but the result I am getting is undesired.Can you please help me in solving the issue.
import java.util.*;
class testMap
{
public static void main(String[] args)
{
HashMap<String,Object> childRowMap = new HashMap<String, Object>();
List <Object> actList= new ArrayList <Object> ();
for (int x=0;x<2 ;x++ ){
if(x==0){
childRowMap.put("startDate","startDate"+x);
childRowMap.put("endDate","endDate"+x);
childRowMap.put("encodedValue"," enc"+x);
}
else if (x==1){
childRowMap.put("startDate","startDate"+x);
childRowMap.put("endDate","endDate"+x);
childRowMap.put("encodedValue"," enc"+x);
}
System.out.println("Adding object in the postition "+ x);
actList.add(x,childRowMap);
}
System.out.println(actList);
}
}
Result:
Adding object in the postition 0
Adding object in the postition 1
[{encodedValue= enc1, startDate=startDate1, endDate=endDate1}, {encodedValue= en
c1, startDate=startDate1, endDate=endDate1}]
===============
Why I am not getting objects with different values.Kindly helping me out in figuring the problem with my code..
You're adding childRowMap twice.
Note that you're adding the reference to childRowMap. This means that changes to the map will be visible from both reference at index 0 and index 1, and that's why it looks like you've added two identical objects.
You could fix it by creating a new map each iteration in the loop:
import java.util.*;
class testMap {
public static void main(String[] args) {
.-------
|
| List<Object> actList = new ArrayList<Object>();
|
| for (int x = 0; x < 2; x++) {
|
'---------> HashMap<String, Object> childRowMap = new HashMap<String, Object>();
if (x == 0) {
childRowMap.put("startDate", "startDate" + x);
childRowMap.put("endDate", "endDate" + x);
childRowMap.put("encodedValue", " enc" + x);
} else if (x == 1) {
childRowMap.put("startDate", "startDate" + x);
childRowMap.put("endDate", "endDate" + x);
childRowMap.put("encodedValue", " enc" + x);
}
System.out.println("Adding object in the postition " + x);
actList.add(x, childRowMap);
}
System.out.println(actList);
}
}
Output:
Adding object in the postition 0
Adding object in the postition 1
[{encodedValue= enc0, startDate=startDate0, endDate=endDate0},
{encodedValue= enc1, startDate=startDate1, endDate=endDate1}]
You need to reinitialize your map on every iteration. Put the initialization inside the for loop:
for(int x = 0; x < 2; x++) {
HashMap<String,Object> childRowMap = new HashMap<String, Object>();
...
}
The problem is that childRowMap is the same instance, created in your first line of code. When you go through the for loop, you aren't creating a new instance, you're just putting new values in the existing HashMap. That means that the ArrayList, performing a referential check, sees that the object is already in the list and doesn't add it twice.
Simple fix: move the initialization inside the for loop, so on each iteration through the loop, the HashMap is re-instantiated.
class testMap {
public static void main(String[] args) {
HashMap<String,Object> childRowMap;
List <Object> actList= new ArrayList <Object> ();
for (int x=0;x<2 ;x++ ){
childRowMap = new HashMap<String, Object>();
if(x==0){
childRowMap.put("startDate","startDate"+x);
childRowMap.put("endDate","endDate"+x);
childRowMap.put("encodedValue"," enc"+x);
} else if (x==1){
childRowMap.put("startDate","startDate"+x);
childRowMap.put("endDate","endDate"+x);
childRowMap.put("encodedValue"," enc"+x);
}
System.out.println("Adding object in the postition "+ x);
actList.add(x,childRowMap);
}
System.out.println(actList);
}
}
There are many issues in your code. It can all be compacted like this:
List <Map<String,Object>> actList= new ArrayList<Map<String,Object>> ();
for (int x=0;x<2 ;x++ ){
Map<String,Object> childRowMap = new HashMap<String, Object>();
childRowMap.put("startDate","startDate"+x);
childRowMap.put("endDate","endDate"+x);
childRowMap.put("encodedValue"," enc"+x);
System.out.println("Adding object in the postition "+ x);
actList.add(childRowMap);
}
System.out.println(actList);
Few other things:
As a Java standard your class name should start with upper case so consider TestMap instead of testMap
Type of Map variable should be generic Map instead of an implementation like HashMap (I have corrected that in my answer).
Consider declaring List as of more specific type List<Map<String,Object>> instead of generic Object for type safety.
As others said, hash map keys should be unique, simplest fix is add this line
HashMap<String,Object> childRowMap = new HashMap<String, Object>();
at the start of the for-loop
Maps store by Key:Value pairs. In your code when you do
childRowMap.put("startDate","startDate"+x)
it is doing this:
childRowMap.put(Key,Value)
So basically you are setting the key startDate to be equal to startDate0 (when x is 0). When you loop through the second time, you are setting the key startDate to be equal to startDate1 (because x is 1). Now whenever you look up startDate, it will only have startDate1 stored because startDate0 was overwritten because you only have 1 Map.
You can fix this by either reinitializing your Map every time you loop through or by using new and unique Key's to each Value you put in the Map.