How To Access The Value in HashTable - java

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());
}
}

Related

How to retrieve data from nested dictionary in java

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.

Java compilation error in this HashMap. Why is the compiler catching an Object being converted into a String?

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.

Get array elements from HashMap in Java

I have a method that puts value in HashMap of type HashMap<String, Object[]> & returns the same HashMap.
Code for putting value in HashMap:
doc = Jsoup.connect(url).get();
for( org.jsoup.nodes.Element element : doc.getAllElements() )
{
for( Attribute attribute : element.attributes() )
{
String option_ID=element.tagName()+"_"+attribute.getKey()+"_"+attribute.getValue();
String HTMLText=element.text();
int HTMLTextSize=HTMLText.length();
if(!HTMLText.isEmpty())
data.put("Test"+i,new Object[{"Test"+i,option_ID,HTMLText,HTMLTextSize});//adding value in HashMap.
i++;
}
}
I tried iterating as below, which I think is not the correct way :
HashMap<String, Object[]>set=HTMLDocument.createHTMLSet("URL of website");
Iterator it = set.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
As I am getting output as :
Test79 = [Ljava.lang.Object;#14e1a0f
Test378 = [Ljava.lang.Object;#1a5f880
How should I iterate over this HashMap to get Object[] values such as option_ID, HTMLText?
Since each object has toString() method, the default displays the class name representation, then adding # sign and then the hashcode, that's why you're getting the output
[Ljava.lang.Object;#14e1a0f
that means the array contains a class or interface.
One solution would be looping on the array and print each part (or using Arrays.toString method), but I highly recommend you wrapping this to your own class and override the toString method.
The following code might help. Its always better to create a bean class consisting of the necessary information to be stored in an array of objects.
package stack.overflow;
import java.util.HashMap;
import java.util.Map;
public class RetrieveMap {
public static void main(String[] args) {
Person p = new Person();
p.setName("John");
p.setEmpNo("1223");
p.setAge("34");
Person p1 = new Person();
p1.setName("Paul");
p1.setEmpNo("1224");
p1.setAge("35");
Person[] arr = new Person[2];
arr[0] = p ;
arr[1] = p1;
HashMap<String,Person[]> map = new HashMap<String,Person[]>();
map.put("a1", arr);
for(Map.Entry<String, Person[]> entry : map.entrySet()) {
System.out.println("Key:" +entry.getKey());
System.out.println("Value:" +entry.getValue());
for(int i=0;i<entry.getValue().length;i++) {
System.out.println("------------------");
System.out.println("Array:"+i);
Person r1 = (Person)entry.getValue()[i];
System.out.println("Name:" +r1.getName());
System.out.println("Age:" + r1.getAge());
System.out.println("Emp no:" + r1.getEmpNo());
System.out.println("------------------");
}
}
}
}
package stack.overflow;
public class Person {
String name;
String age;
String empNo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getEmpNo() {
return empNo;
}
public void setEmpNo(String empNo) {
this.empNo = empNo;
}
}
The short answer is your code is behaving exactly correctly; when you call .toString() on an Object[] (which happens implicitly with System.out.println()) you get that odd [<TYPE>#<IDENTIFIER> string. To print the contents of an array, use Arrays.toString().
There are a number of things we can clean up with this code, though.
Avoid mixing generics and arrays (Effective Java Item 25); arrays lack the type safety generics provide, and there's rarely a good reason to use them in modern generic code. A better type signature would be HashMap<String, List<Object>>. This is effectively identical, but in practice much easier to work with.
Don't use arrays to store different types. You appear to be storing a "Test" string, a identifier string, the element's text, and the text's length as fields in an array. This is what objects are for. Define an object with those four fields, and pass them into the constructor. Even better, since everything but i is computable from the element, just pass the element into the constructor and compute the information you need (HTML string, length, etc.) in the constructor or even in the class' getters.
Don't use raw types (Effective Java Item 23) for Iterators and Map.Entrys. Your IDE can warn you when you use raw types so you avoid this common programming error. In your code you should use Iterator<Entry<String, Object[]>> and Entry<String, Object[]>
Don't use Iterator to loop over a Map's elements, use a for-each loop:
for (Entry<String, ...> e : map.entrySet()) {
...
}
Don't call a Map variable a set; they're different things. Similarly a Map.Entry is not a pair - it specifically represents a key-value relationship.
Here's a cleaned-up version of your code, assuming a Container object exists that takes an Element and extracts the data you need.
doc = Jsoup.connect(url).get();
for (org.jsoup.nodes.Element element : doc.getAllElements()) {
for (Attribute attribute : element.attributes()) {
Container c = new Container(i++, attribute);
data.put(c.getKey(), c);
}
}
And:
HashMap<String, Container> map = HTMLDocument.createHTMLMap("URL of website");
for (Entry<String, Container> e : map.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
The value is array of Object. Try following instead
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue()[0].toString());
}

Check if 'Key' exists in a hashmap [duplicate]

This question already has answers here:
HashMap<String, Integer> Search for part of an key? [duplicate]
(8 answers)
Closed 8 years ago.
I have a hashmap with Key and Value being 'String'. I want to check if a particular key exists by ignoring string after '$' in the Key.
Hashmap contains keys as 'acctId$accountId', 'acctId$desc', 'acctId$crncyCode' etc.
Iterator itx = uiToSrvFldMapList.entrySet().iterator();
if(uiToSrvFldMapList.containsKey(cellId)){
String sSrvFld = (String) uiToSrvFldMapList.get("acctId");
System.out.println("sSrvFld :: " +sSrvFld);
public static void main(String[] args) {
String s = "acctId$accountId";
s = s.replaceAll("\\$.*", "");// remove everything after $
System.out.println(s);
// do hm.get(s) here
}
I hope this might help you
Map map = new HashMap();
map.put("abc$def","ABC");
map.put("ab","A");
map.put("de","b");
String key = "abc$def";
String s[] = key.split("$");
if(map.containsKey(s[0]))
System.out.println("Value is: "+map.get(key));
else
System.out.println("cannot find..");
Supposing that in "acctId$accountId" you will have the same String both as "acctId" and "accountId", you can search for it in the following way:
`Map<String, String> uiToSrvFldMapList = new HashMap<String, String>();
uiToSrvFldMapList.put("0000$0000", "test"); // just an example
uiToSrvFldMapList.put("0000$0001", "description"); // just an example
uiToSrvFldMapList.put("0001$0000", "2test"); // just an example
uiToSrvFldMapList.put("0001$0001", "2description"); // just an example
String acctId = "0000"; // the account id string
if(uiToSrvFldMapList.containsKey(acctId +"$" + acctId)){
String sSrvFld = (String) uiToSrvFldMapList.get(acctId + "$" + acctId);
System.out.println("sSrvFld :: " +sSrvFld);
}`
This is a test program, which shows a way to achieve this functionality:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Test {
public static void main(String[] args) {
Map<String, String> uiToSrvFldMapList = new HashMap<String, String>();
uiToSrvFldMapList.put("acctId$accountId", "accid");
uiToSrvFldMapList.put("acctId$desc", "accdesc");
uiToSrvFldMapList.put("acctId$crncyCode", "currencyCode");
uiToSrvFldMapList.put("smthElse$smthElse", "smthElse");
List<String> valuesContainingKey = valuesContainingKeys(
uiToSrvFldMapList, "acctId");
// Returns if the key is contained
if (valuesContainingKey.isEmpty()) {
System.out.println("The key is not contained in the map");
} else {
System.out.println("The part of the key is in the map");
}
System.out
.println("All values, where the corresponding key contains the subkey: ");
for (String s : valuesContainingKey) {
System.out.println(s);
}
}
/**
*
* #param map
* Map containing the key-value pairs
* #param searchString
* A String used as a subkey, for which is searched if it is
* contained as a substring at the beginning of a key in the map
* #return List of all Values from the map, whose corresponding key contains
* searchString
*/
private static List<String> valuesContainingKeys(Map<String, String> map,
String searchString) {
List<String> containingKeys = new ArrayList<String>();
for (Entry<String, String> e : map.entrySet()) {
if (e.getKey().startsWith(searchString)) {
containingKeys.add(e.getValue());
}
}
return containingKeys;
}
}
Simply write the method valuesContainingKeys (not needed to be static) where you want this functionality. This method will return a list of all values, whose corresponding key contains the string you are looking for. Simply checking valuesContainingKey.isEmpty() will return if there is no value, for which the corresponding key begins with the searched key.

How to Print treemap in reverse order

In my assignment we are read from a file the text:
To be, or not to be: that is the question:
Whether 'tis nobler in the mind to suffer
then count the times each has occured. I've been able to print this map unsorted, then I was able to make a TreeMap and print it in natural order (which is shown below). I don't know how to print in reverse order. I know a way to use a comparator, but I'm a little rusty so I've done what I can. Furthermore, I don't know how to set the comparator up to sort the Treemap into reverse order.
Here's my method to print Unsorted and Naturally sorted:
private static void sortPrintFrequencies(Map<String,Integer> vocabulary, PrintStream output {
Iterator iterator = vocabulary.keySet().iterator();
System.out.println("Unsorted");
while (iterator.hasNext()) {
String key = iterator.next().toString();
String value = vocabulary.get(key).toString();
String times = "times.";
String appears = "appears";
System.out.printf("%35s", key + " " + appears + " " + value + " "+ times);
System.out.println();
}
System.out.println("========================================");
System.out.println("SORTED NATURALLY BY KEY");
TreeMap newVocabulary = new TreeMap(vocabulary);
Iterator iterator2 = newVocabulary.keySet().iterator();
while (iterator2.hasNext()) {
String key = iterator2.next().toString();
String value = newVocabulary.get(key).toString();
String times = "times.";
String appears = "appears";
System.out.printf("%35s", key + " " + appears + " " + value + " "+ times);
System.out.println();
}
TreeMap revVocabulary = new TreeMap(new RevCmpKey());
System.out.println("========================================");
}
Here's my comparator:
import java.util.*;
public class RevCmpKey implements Comparator<String> {
public int compare(String e1, String e2) {
//compareTo in String classs
if(e1.compareTo(e2) <1)return -1;
if(e1.compareTo(e2) >1)return 1;
return 0;
}
}
What about copying your Map into a new one naturally reverse ordered?
new TreeMap<String,Integer>(Collections.reverseOrder())
Short Answer:
Use descendingKeySet or descendingMap.
Long Answer:
Solution 1:
As Oliver correctly mentioned, you can copy the map into a new TreeMap to reach your goal.
However, when using descendingKeySet, you won't need to create a new TreeMap:
treeMap.descendingKeySet()
Here's an example:
private static void printReverseTreeMap(TreeMap<String,Integer> treeMap){
for(String key : treeMap.descendingKeySet()){
System.out.println("value of " + key + " is " + treeMap.get(key));
}
}
Solution 2:
You can also create a new Map in reverse order using descendingMap as well as Collections.reverseOrder():
NavigableMap<String, Integer> reveresedTreeMap = treeMap.descendingMap();
Note that descendingMap returns NavigableMap.
Since String is already comparable, the inverse Comparator is trivial:
public class RevCmpKey implements Comparator<String> {
public int compare(String e1, String e2) {
return - e1.compareTo(e2);
}
}
The other problem is that you are not specifying the values for the Generics; When you construct the TreeMap, you should use
TreeMap<String, Integer> revVocabulary = new TreeMap<String, Integer>(new RevCmpKey());
Then you just call putAll and that is enough
Here you can also prepare a ReverseComparator and use for any class, used in Ordered-Collection :
class ReverseComparator implements Comparator<Comparable<Object>> {
#Override
public int compare(Comparable<Object> o1, Comparable<Object> o2) {
return o2.compareTo( o1 );
}
}
As usually we compare o1 with o2, but for reverse compare o2 with o1
Just try below
private TreeMap<BigInteger, List<TicketingDocumentServiceCouponHistory>> getCpnHistoryMap(
List<TicketingDocumentHistory> tktHistoryList,List<TicketingDocumentServiceCouponTicket> couponList){
TreeMap<BigInteger, List<TicketingDocumentServiceCouponHistory>> cpnHistoryMap = new TreeMap<>(Collections.reverseOrder());
cpnHistoryMap.put(BigInteger.valueOf(Integer.MAX_VALUE), getOcCpnHistoryList(couponList));
tktHistoryList
.stream()
.filter(history -> history.getCode().equals(RVL))
.forEach(history -> cpnHistoryMap.put(history.getSequence(), getCpnHistoryList(cpnHistoryMap, history)));
TreeMap<BigInteger, List<TicketingDocumentServiceCouponHistory>> cpnHistMapInOrder = new TreeMap<>();
cpnHistMapInOrder.putAll(cpnHistoryMap);
return cpnHistMapInOrder;
}

Categories

Resources