How to Print treemap in reverse order - java

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

Related

Getting the path from a hash map key (Java)

My hashmap key returns this: MemorySection[path='rr', root='YamlCofiguration']=1
Is there anyway I can get the value of path=''. I know that I can get the value of the root='' using getValue(), although I only really use this for keeping track of the highest and lowest values to then order them from highest to lowest.
I have tried this thread although the answers presume that I would know what the pair's name is. Retrieving Key from the Hash Map
EDIT:
Here is how I'm setting the data and sorting it as well. I am accessing it through the likesList List
HashMap<String, Integer> likes = new HashMap<>();
for(String key: playersFile.getKeys(false)) {
likes.put(playersFile.getString(key), playersFile.getInt(key + ".likes"));
}
List<Entry<String, Integer>> likesList = new LinkedList<Entry<String, Integer>>(likes.entrySet());
Collections.sort(likesList, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
for (int i = 0; i<45; i++) {
try {
String name1 = cookiesList.get(i).getKey();
item = name(name1);
publicinv.setItem(i, item);
} catch (IndexOutOfBoundsException e) {
}
}
I still don't really know what you want, but here is a guess I made:
// your input
String name1 = "MemorySection[path='rr', root='YamlCofiguration']=1";
// this string indicates the start of the path
String start = "path='";
// where the path starts
int pathStart = name1.indexOf(start)+start.length();
// where the path ends
int pathEnd = name1.substring(pathStart).indexOf("'") + pathStart;
// get the path
System.out.println( name1.substring(pathStart, pathEnd) ); // prints: rr

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

List of string with occurrences count and sort

I'm developing a Java Application that reads a lot of strings data likes this:
1 cat (first read)
2 dog
3 fish
4 dog
5 fish
6 dog
7 dog
8 cat
9 horse
...(last read)
I need a way to keep all couple [string, occurrences] in order from last read to first read.
string occurrences
horse 1 (first print)
cat 2
dog 4
fish 2 (last print)
Actually i use two list:
1) List<string> input; where i add all data
In my example:
input.add("cat");
input.add("dog");
input.add("fish");
...
2)List<string> possibilities; where I insert the strings once in this way:
if(possibilities.contains("cat")){
possibilities.remove("cat");
}
possibilities.add("cat");
In this way I've got a sorted list where all possibilities.
I use it like that:
int occurrence;
for(String possible:possibilities){
occurrence = Collections.frequency(input, possible);
System.out.println(possible + " " + occurrence);
}
That trick works good but it's too slow(i've got millions of input)... any help?
(English isn’t my first language, so please excuse any mistakes.)
Use a Map<String, Integer>, as #radoslaw pointed, to keep the insertion sorting use LinkedHashMap and not a TreeMap as described here:
LinkedHashMap keeps the keys in the order they were inserted, while a TreeMap is kept sorted via a Comparator or the natural Comparable ordering of the elements.
Imagine you have all the strings in some array, call it listOfAllStrings, iterate over this array and use the string as key in your map, if it does not exists, put in the map, if it exists, sum 1 to actual result...
Map<String, Integer> results = new LinkedHashMap<String, Integer>();
for (String s : listOfAllStrings) {
if (results.get(s) != null) {
results.put(s, results.get(s) + 1);
} else {
results.put(s, 1);
}
}
Make use of a TreeMap, which will keep ordering on the keys as specified by the compare of your MyStringComparator class handling MyString class which wraps String adding insertion indexes, like this:
// this better be immutable
class MyString {
private MyString() {}
public static MyString valueOf(String s, Long l) { ... }
private String string;
private Long index;
public hashcode(){ return string.hashcode(); }
public boolean equals() { // return rely on string.equals() }
}
class MyStringComparator implements Comparator<MyString> {
public int compare(MyString s1, MyString s2) {
return -s1.getIndex().compareTo(s2.gtIndex());
}
}
Pass the comparator while constructing the map:
Map<MyString,Integer> map = new TreeMap<>(new MyStringComparator());
Then, while parsing your input, do
Long counter = 0;
while (...) {
MyString item = MyString.valueOf(readString, counter++);
if (map.contains(item)) {
map.put(map.get(item)+1);
} else {
map.put(item,1);
}
}
There will be a lot of instantiation because of the immutable class, and the comparator will not be consistent with equals, but it should work.
Disclaimer: this is untested code just to show what I'd do, I'll come back and recheck it when I get my hands on a compiler.
Here is the complete solution for your problem,
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DataDto implements Comparable<DataDto>{
public int count = 0;
public String string;
public long lastSeenTime;
public DataDto(String string) {
this.string = string;
this.lastSeenTime = System.currentTimeMillis();
}
public boolean equals(Object object) {
if(object != null && object instanceof DataDto) {
DataDto temp = (DataDto) object;
if(temp.string != null && temp.string.equals(this.string)) {
return true;
}
}
return false;
}
public int hashcode() {
return string.hashCode();
}
public int compareTo(DataDto o) {
if(o != null) {
return o.lastSeenTime < this.lastSeenTime ? -1 : 1;
}
return 0;
}
public String toString() {
return this.string + " : " + this.count;
}
public static final void main(String[] args) {
String[] listOfAllStrings = {"horse", "cat", "dog", "fish", "cat", "fish", "dog", "cat", "horse", "fish"};
Map<String, DataDto> results = new HashMap<String, DataDto>();
for (String s : listOfAllStrings) {
DataDto dataDto = results.get(s);
if(dataDto != null) {
dataDto.count = dataDto.count + 1;
dataDto.lastSeenTime = System.nanoTime();
} else {
dataDto = new DataDto(s);
results.put(s, dataDto);
}
}
List<DataDto> finalResults = new ArrayList<DataDto>(results.values());
System.out.println(finalResults);
Collections.sort(finalResults);
System.out.println(finalResults);
}
}
Ans
[horse : 1, cat : 2, fish : 2, dog : 1]
[fish : 2, horse : 1, cat : 2, dog : 1]
I think this solution will be suitable for your requirement.
If you know that your data is not going to exceed your memory capacity when you read it all into memory, then the solution is simple - using a LinkedList or a and a LinkedHashMap.
For example, if you use a Linked list:
LinkedList<String> input = new LinkedList();
You then proceed to use input.add() as you did originally. But when the input list is full, you basically use Jordi Castilla's solution - but put the entries in the linked list in reverse order. To do that, you do:
Iterator<String> iter = list.descendingIterator();
LinkedHashMap<String,Integer> map = new LinkedHashMap<>();
while (iter.hasNext()) {
String s = iter.next();
if ( map.containsKey(s)) {
map.put( s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
Now, the only real difference between his solution and mine is that I'm using list.descendingIterator() which is a method in LinkedList that gives you the entries in backwards order, from "horse" to "cat".
The LinkedHashMap will keep the proper order - whatever was entered first will be printed first, and because we entered things in reverse order, then whatever was read last will be printed first. So if you print your map the result will be:
{horse=1, cat=2, dog=4, fish=2}
If you have a very long file, and you can't load the entire list of strings into memory, you had better keep just the map of frequencies. In this case, in order to keep the order of entry, we'll use an object such as this:
private static class Entry implements Comparable<Entry> {
private static long nextOrder = Long.MIN_VALUE;
private String str;
private int frequency = 1;
private long order = nextOrder++;
public Entry(String str) {
this.str = str;
}
public String getString() {
return str;
}
public int getFrequency() {
return frequency;
}
public void updateEntry() {
frequency++;
order = nextOrder++;
}
#Override
public int compareTo(Entry e) {
if ( order > e.order )
return -1;
if ( order < e.order )
return 1;
return 0;
}
#Override
public String toString() {
return String.format( "%s: %d", str, frequency );
}
}
The trick here is that every time you update the entry (add one to the frequency), it also updates the order. But the compareTo() method orders Entry objects from high order (updated/inserted later) to low order (updated/inserted earlier).
Now you can use a simple HashMap<String,Entry> to store the information as you read it (I'm assuming you are reading from some sort of scanner):
Map<String,Entry> m = new HashMap<>();
while ( scanner.hasNextLine() ) {
String str = scanner.nextLine();
Entry entry = m.get(str);
if ( entry == null ) {
entry = new Entry(str);
m.put(str, entry);
} else {
entry.updateEntry();
}
}
Scanner.close();
Now you can sort the values of the entries:
List<Entry> orderedList = new ArrayList<Entry>(m.values());
m = null;
Collections.sort(orderedList);
Running System.out.println(orderedList) will give you:
[horse: 1, cat: 2, dog: 4, fish: 2]
In principle, you could use a TreeMap whose keys contained the "order" stuff, rather than a plain HashMap like this followed by sorting, but I prefer not having either mutable keys in a map, nor changing the keys constantly. Here we are only changing the values as we fill the map, and each key is inserted into the map only once.
What you could do:
Reverse the order of the list using
Collections.reverse(input). This runs in linear time - O(n);
Create a Set from the input list. A Set garantees uniqueness.
To preserve insertion order, you'll need a LinkedHashSet;
Iterate over this set, just as you did above.
Code:
/* I don't know what logic you use to create the input list,
* so I'm using your input example. */
List<String> input = Arrays.asList("cat", "dog", "fish", "dog",
"fish", "dog", "dog", "cat", "horse");
/* by the way, this changes the input list!
* Copy it in case you need to preserve the original input. */
Collections.reverse(input);
Set<String> possibilities = new LinkedHashSet<String>(strings);
for (String s : possibilities) {
System.out.println(s + " " + Collections.frequency(strings, s));
}
Output:
horse 1
cat 2
dog 4
fish 2

How to sort an array of objects w.r.t. key using Java?

My question might seem ditto duplicate, but I have seen several questions and could not satisfy my quest.
I have a data like this:
index value
1 220
2 123
3 11123
4 440
5 3400
I have saved it into String[] data= new String[5]; as following:
data[0]= 1 + " " + 220;
data[1]= 2 + " " + 123;
...
Now what I do is:
Arrays.sort(data);
What it does is sorting, but w.r.t. 1st column.
I want this to do it for me w.r.t. 2nd column.
Is it possible or if I am wrong?
Also I am not sure if this is the right way I have used to save this kind of data?
How about, if I want to use int(s) to save these values, how will everything go?
i.e. from saving data to get it sorted in formal Java style?
EDIT: This is a two columns case, where I have said index and value. I am particularly interested in a case with more than two columns and different data types. Where sorting should be performed w.r.t. the elements of any column specified.
Create a class to hold your two related data elements (index and value) as fields (presumably with getters and setters). Write two Comparator classes, one that sorts by index and one that sorts by value. I would probably create factory methods in the class to get these Comparators.
Rather than create an array of String, you would create an array of your new class. Construct your class instances and assign to the array.
Than you can use Arrays.sort on your array with whichever Comparator is appropriate to efficiently sort the array. This also allows you easy access to the individual fields.
Bro - here is some code to get you started...
public class Bro {
private int index;
private int value;
public Bro (int index, int value) {
this.index = index;
this.value = value;
}
public static Comparator<Bro> getIndexComparator() {
return new Comparator<Bro>() {
public int compare(Bro o1, Bro o2) {
return o1.index - o2.index;
}
}
}
}
Bro[] bros = new Bro[5];
bros[0] = new Bro(1, 220);
...
Arrays.sort(bros, Bro.getIndexComparator());
Java provides two similar interfaces: Comparator and Comparable. If a class has a natural sort order, you would implement Comparable. If you need to sort a class in more than one way, you will implement a Comparator for each sort order that you need.
I would suggest to use a Tuple class to hold your key/values and then use a comparator to
sort based on keys/values. Something like the following. It's written using Java 8.
class Main {
public static void main(String[] args) {
Tuple[] data = new Tuple[5];
data[0] = new Tuple(1, 220);
data[1] = new Tuple(2, 123);
data[2] = new Tuple(3, 11123);
data[3] = new Tuple(4, 440);
data[4] = new Tuple(5, 3400);
Arrays.sort(data, (t1, t2) -> t1.value - t2.value);
}
}
class Tuple {
int key;
int value;
public Tuple(int key, int value) {
this.key = key;
this.value = value;
}
#Override
public String toString() {
return "(" + key + ", " + value + ")";
}
}
About the general case, I'm afraid in Java you cannot define a type with unknown number of generic types. But if you know beforehand how many columns yo have, you can do the following:
class Tuple<T1 extends Comparable<T1>, T2 extends Comparable<T2>, ..., Tn extends Comparable<Tn>> {
T1 col_1;
T2 col_2;
...
Tn col_n;
public Tuple(T1 col_1, T1 col_2, ..., Tn col_n) {
this.col_1 = col_1;
this.col_2 = col_2;
...
this.col_n = col_n;
}
#Override
public String toString() {
return "(" + col_1 + ", " + ... + col_n + ")";
}
}
And then sort based on the column number as follows:
Arrays.sort(data, (t1, t2) -> t.col_i.compareTo(t2.col_i))
So essentially, each column type knows how to compare itself with its own type.
You can use a custom comparator to re-split the strings only during the comparisons, and compare using the int values. So instead of using
Arrays.sort(data);
You should use:
Arrays.sort(data, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
int val1 = Integer.valueOf(o1.split(" ")[1]);
int val2 = Integer.valueOf(o2.split(" ")[1]);
// Ascending
if (val1 > val2) {
return 1;
} else if (val1 == val2) {
return 0;
}
return -1;
}
});
You might want to consider using a Map for this kind of data. With index as key and value as the data associated with the key.
Or the the other way round if you want to sort using value mostly.
Something like:
TreeMap<Integer, Integer> dataMap = new TreeMap<>(); //sorts the entries according to key
dataMap.add(220, 1);
dataMap.add(123, 2);
...
You can further lookup bunch of methods to iterate over TreeMap here.

How To Access The Value in HashTable

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

Categories

Resources