How to find all descendants from flat tree structure - java

I have a flat data that represent the hierarchical relationship as below:
ID Name PID
0 A NULL
1 B 0
2 C 0
4 D 1
5 E 1
6 F 4
3 G 0
This table represents the 'data table', where PID indicates the parent element.
For example, in the first row we see that A has PID null whereas B has PID 0, which means that B’s parent is A, because 0 is the ID of A, and A is the root element, because it does not have a PID. Similarly, C has parent A because C too has PID 0, and 0 is the ID of A.
I create a class RecordHolder to represent the above table. I also implement the method processRecordHolder
public Map<String, List<String>> processRecordHolder()
The returned map uses element as keys, and holds collections of descendant nodes as values. For example, the first item in the map corresponds to element A, which has many descendants, whereas element C has no descendant. The order of members in the output is not important.
public static void main(String[] args) {
RecordHolder dt = new RecordHolder();
dt.addRow(0, "A", null);
dt.addRow(1, "B", 0);
dt.addRow(2, "C", 0);
dt.addRow(4, "D", 1);
dt.addRow(5, "E", 1);
dt.addRow(6, "F", 4);
dt.addRow(3, "G", 0);
System.out.println("Output:");
System.out.println(dt.processRecordHolder());
}
Output:
{D=[F], A=[B, C, G, D, E, F], B=[D, E, F]}
or
{D=[F], E=null, F=null, G=null, A=[B, C, G, D, E, F], B=[D, E, F], C=null}
Below is my implementation of Record which I am able to come up so far:
public class Record {
public Integer id;
public String name;
public Integer parentId;
public Record parent;
public Collection<Record> children;
public Record(Integer id, String name, Integer parentId) {
this();
this.id = id;
this.name = name;
this.parentId = parentId;
}
public Record() {
children = Collections.newSetFromMap(new ConcurrentHashMap<Record, Boolean>())
}
public Collection<Record> getChildren() {
return children;
}
public Record getParent() {
return parent;
}
public Integer getParentId() {
return parentId;
}
#Override
public String toString() {
return "Record{" + "id=" + id + ", name=" + name + ", parentId=" + parentId + '}';
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Record)) {
return false;
}
Record other = (Record) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (parentId == null) {
if (other.parentId != null) {
return false;
}
} else if (!parentId.equals(other.parentId)) {
return false;
}
return true;
}
}
Now I am not able to understand other step what should I do?

Try:
public class RecordHolder {
Map<Integer,String> namesById = new HashMap<>();
Map<Integer,List<Integer>> childrenById = new HashMap<>();
public void addRow(Integer id, String name, Integer parent) {
namesById.put(id, name);
List<Integer> children = childrenById.get(parent);
if (children == null) {
children = new ArrayList<>();
childrenById.put(parent, children);
}
children.add(id);
}
public Map<String,List<String>> processRecordHolder() {
Map<String,List<String>> results = new HashMap<>();
descendants(null, results);
return results;
}
private List<String> descendants(Integer id, Map<String, List<String>> results) {
final List<String> childrenNames = new ArrayList<>();
final List<Integer> childrenIds = childrenById.get(id);
if (childrenIds != null && childrenIds.size() > 0) {
for (Integer childrenId : childrenIds) {
final String childName = namesById.get(childrenId);
childrenNames.add(childName);
final List<String> grandchildrenNames = descendants(childrenId, results);
childrenNames.addAll(grandchildrenNames);
}
if (id != null) {
results.put(namesById.get(id), childrenNames);
}
}
return childrenNames;
}
}

Just in case you'd like to try my simpler idea for implementation, here it is in brief detail. This way, you can decide whether you want to use your current idea or try to start over using this idea. (note the code below is presented as a pseudo-Java outline, it won't compile and is not tested):
int numNodes = 7;
Node[] nodes = new Node[numNodes];
//Read in your file here using a Scanner/FileReader or something
int ID = 0;
char value = 0;
int PID = 0;
while(scanner.hasNextLine()){
ID = scan.next();
value = scan.next();
PID = scan.next();
nodes[ID] = new Node(value, PID);
}
And then a node class:
class Node{
char value;
Node parent;
public Node(value, parentID){
this.value = value;
if(parentID == -1)
parent = null;
else
parent = nodes[parentID]; //nodes will have to be a global array or get passed to the constructor
}
}
Note that this constructor will only work if the item in nodes[parentID] has been initialized previously. (This is the case for your current input file order, but might not be in other situations.)
Ancestry:
To find the ancestry of a node using ID with this approach simply do:
printAncestry(nodes[ID]);
void printAncestry(Node n){
System.out.println("Child: " + n.value);
System.out.println("Ancestry: ");
while(n.parent != null){
n = n.parent;
System.out.println(n.value);
}
}

Related

recursion not navigating all child nodes

I need to navigate my 23Tree and print all the levels and corresponding elements. However, my recursion goes in any one direction and does not return and perform other calls. Any help would be much appreciated.
Here is my node class:
class Node<T extends Comparable<T>> {
List<T> vals = new ArrayList<T>();
List<Node<T>> children = new ArrayList<Node<T>>();
boolean isLeaf() { return children.size() == 0; }
boolean is4Node() { return vals.size() == 3; }
// new Nodes always are 2-nodes (1 value). The node may be
// a leaf, or has 2 children.
Node(T x) {
vals.add(x);
}
Node(T x, Node<T> left, Node<T> right) {
vals.add(x);
children.add(left);
children.add(right);
children.add(null); // hack
}
This is my recursive function to print the nodes:
private boolean iterateChildrenAndPrintPerLevelAndLevelType(int level, String levelType, Node root){
System.out.println("present element: " + root);
if(root.vals.size() == 1 ){
System.out.println("Level = " + level + " [" + levelType + "] value = " + root.vals.get(0));
}else if(root.vals.size() == 2 ){
System.out.println("Level = " + level + " [" + levelType + "] value = " + root.vals.get(0) + "/" + root.vals.get(1));
}
if(root.children.get(0) != null){
iterateChildrenAndPrintPerLevelAndLevelType(level+1, "left", (Node) root.children.get(0));
}
if(root.children.get(1) != null){
iterateChildrenAndPrintPerLevelAndLevelType(level+1, "middle", (Node) root.children.get(1));
}
if(root.children.get(2) != null){
iterateChildrenAndPrintPerLevelAndLevelType(level+1, "right", (Node) root.children.get(2));
}
return true;
}
And here is the output:
present element: [[[a]b[c]]d, [[e]f[g]]h[[i]j, [k]y[z]]]
Level = 0 [root] value = d/h
present element: [[a]b[c]]
Level = 1 [left] value = b
present element: [a]
Level = 2 [left] value = a
(Edit) Here is my main method:
public static void main(String[] args) {
StringTwoThreeTree set = new StringTwoThreeTree();
try{
String line = null;
FileReader fileReader =
new FileReader("C:\\Users\\Redoubt\\IdeaProjects\\23Tree\\src\\resources\\test.dat");
// new FileReader("C:\\Users\\Redoubt\\IdeaProjects\\23Tree\\src\\resources\\a4q1search.txt");
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
set.insert(line);
}
// System.out.println("\n\n\n");
String str = set.toString();
// System.out.println(str);
set.print();
}catch (Exception e){
}
}
and the contents of the file test.dat :
a
a
b
c
d
e
f
g
h
i
j
k
y
z
Just for clarity, I'm adding the 2 large classes as well:
StringTwoThree class:
import java.util.List;
public class StringTwoThreeTree extends TwoThreeTree<String> {
#Override
public String toString() {
return super.toString();
}
public void insert(String str){
super.add(str);
}
public void print(){
Node root = super.root;
// System.out.println(root.vals);
// dumpList("",root);
iterateChildrenAndPrintPerLevelAndLevelType(0, "root", root);
super.displayLevelWise();
}
private void dumpList(String string, Node list) {
int i = 0;
for (Object item : list.children) {
if (item instanceof List) {
dumpList(string + i, (Node) item);
} else {
System.out.println(String.format("%s%d %s", string, i, item));
}
++i;
}
}
private boolean iterateChildrenAndPrintPerLevelAndLevelType(int level, String levelType, Node root){
System.out.println("present element: " + root);
if(root.vals.size() == 1 ){
System.out.println("Level = " + level + " [" + levelType + "] value = " + root.vals.get(0));
}else if(root.vals.size() == 2 ){
System.out.println("Level = " + level + " [" + levelType + "] value = " + root.vals.get(0) + "/" + root.vals.get(1));
}
if(root.children.get(0) != null){
iterateChildrenAndPrintPerLevelAndLevelType(level+1, "left", (Node) root.children.get(0));
}
if(root.children.get(1) != null){
iterateChildrenAndPrintPerLevelAndLevelType(level+1, "middle", (Node) root.children.get(1));
}
if(root.children.get(2) != null){
iterateChildrenAndPrintPerLevelAndLevelType(level+1, "right", (Node) root.children.get(2));
}
return true;
}
}
TwoThreeTree class:
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Queue;
public class TwoThreeTree<T extends Comparable<T>> implements Iterable<T> {
// a Node has 1 (2-Node) or 2 (3-Node) values
// and 2 or 3 children. Values and children are stored
// in ArrayLists. If there are children, that ArrayList
// has a null element at the end, so as to make easier the
// method which adds a new child.
class Node<T extends Comparable<T>> {
List<T> vals = new ArrayList<T>();
List<Node<T>> children = new ArrayList<Node<T>>();
boolean isLeaf() { return children.size() == 0; }
boolean is4Node() { return vals.size() == 3; }
// new Nodes always are 2-nodes (1 value). The node may be
// a leaf, or has 2 children.
Node(T x) {
vals.add(x);
}
Node(T x, Node<T> left, Node<T> right) {
vals.add(x);
children.add(left);
children.add(right);
children.add(null); // hack
}
public String toString() {
String answer = "[";
for (int i=0; i<vals.size(); i++) {
if (i != 0) answer += ", ";
if (children.size() != 0)
answer += children.get(i).toString();
answer += vals.get(i);
}
if (children.size() != 0)
answer += children.get(children.size()-2).toString();
return answer + "]";
}
// used in Iterator
void getVals(List<T> iteratorList) {
for (int i=0; i<vals.size(); i++) {
if (children.size() != 0)
children.get(i).getVals(iteratorList);
iteratorList.add(vals.get(i));
}
if (children.size() != 0)
children.get(children.size()-2).getVals(iteratorList);
}
// recursively adds a new value to a subtree
boolean add(T val) {
if (isLeaf())
return addToLeaf(val);
else return addToInterior(val);
}
// new values are always added to a leaf. The result may be a 4-node leaf.
boolean addToLeaf(T x) {
int cmp;
// size is 1 for a 2-node, or 2 for a 3-node
for (int i = 0; i < vals.size(); i++) {
cmp = x.compareTo(vals.get(i));
if (cmp == 0) return false;
else if (cmp < 0) {
vals.add(i,x);
return true;
}
}
vals.add(x);
return true;
}
// adds a value to a subtree rooted by an interior node. If
// the addition results in one of the children being a 4-node,
// then adjustments are made.
boolean addToInterior(T x) {
int cmp;
// size is 1 for a 2-node, or 2 for a 3-node
for (int i = 0; i <= vals.size(); i++) {
if (i == vals.size()) cmp = -1; // hack because there is no vals[2]
else cmp = x.compareTo(vals.get(i));
if (cmp == 0) return false;
else if (cmp < 0) {
boolean retVal = children.get(i).add(x);
if (children.get(i).is4Node())
childIs4Node(i);
return retVal;
}
}
return false; // unreachable -- just for compiler
}
// the ith child is a 4-node
void childIs4Node(int i) {
Node<T> the4Node = children.get(i);
// move the middle value from the 4-node child up
// to its parent
if (i == 2)
vals.add(children.get(i).vals.get(1));
else vals.add(i, children.get(i).vals.get(1));
Node<T> newChild1, newChild2;
if (children.get(i).isLeaf()) {
newChild1 = new Node<T>(children.get(i).vals.get(0));
newChild2 = new Node<T>(children.get(i).vals.get(2));
}
else {
newChild1 = new Node<T>(children.get(i).vals.get(0),
children.get(i).children.get(0),
children.get(i).children.get(1));
newChild2 = new Node<T>(children.get(i).vals.get(2),
children.get(i).children.get(2),
children.get(i).children.get(3));
}
children.remove(the4Node);
children.add(i, newChild2);
children.add(i, newChild1);
}
}
Node<T> root;
public TwoThreeTree() {
root = null;
}
// TwoThreeTree add
public boolean add(T val) {
if (root == null) {
root = new Node<T>(val);
return true;
}
else {
boolean isNew = root.add(val);
// if root is a 4-node, split it
if (root.vals.size() == 3) {
Node<T> left, right;
if (root.isLeaf()) {
left = new Node<T>(root.vals.get(0));
right = new Node<T>(root.vals.get(2));
}
else {
left = new Node<T>(root.vals.get(0),
root.children.get(0),
root.children.get(1));
right = new Node<T>(root.vals.get(2),
root.children.get(2),
root.children.get(3));
}
root = new Node<T>(root.vals.get(1), left, right);
}
return isNew;
}
}
// this method creates a list containing all of the values in
// the tree and returns that list's iterator
public Iterator<T> iterator() {
List<T> vals = new ArrayList<T>();
if (root != null) root.getVals(vals);
return vals.iterator();
}
public String toString(){
String result = "[";
for (T item : this
) {
result += item.toString() + ",";
}
result = result.substring(0,result.length()-1);
result += "]";
return result;
}
public void displayLevelWise(){
}
}
Your index is going out of bound in your private boolean iterateChildrenAndPrintPerLevelAndLevelType(int level, String levelType, Node root) method.

How to check if all employee in hashmap have name?

I have a HashMap of employees:
Employee{
String name;
String id;
String Salary;
}
Map<String,Employee> emps = new HashMap<>();
emps.put("1",employee1);
emps.put("2",employee2);
emps.put("3",employee3);
I want have following scenarios:
All employees have name ==> Pass
All employess dont have name(name=null) ==> Pass
3. Other cases must throw an exception.
Example: employee2 does not have a name, but employee1 and employee3 do.
How can I write such scenario?
You can use Streams to filter employees that have or don't have a name, count them and compare the result to the size of the list.
long count = emps.values()
.stream()
.filter(employee -> employee.getName() != null)
.count();
/**
* count == 0 => All employess dont have name
* count == size => All employees have name
*/
return count == 0 || count == employees.size();
You can iterate over the values of the map by calling (map.values()) ,which give you Collection .Then apply your logic.
Collection<Employee> values = emps.values();
int count = 0;
for (Employee employee : values) {
if(null != employee.name){
count ++;
}
}
return count == 0 || count == emps.size();
1) Get list of employees
Collection<Employee> employees = employeesMap.values();
testEmployees(employees);
The program will stop with an exception if employees do not pass the test. This is how to test them
public void testEmployees(List<Employee> employees) {
int nullNameEmployeeCount = 0;
int size = employes.size();
for (Employee employee : employees) {
if (employee.getName() == null) {
nullNameEmployeeCount++;
}
}
if (nullNameEmployeeCount == 0 || nullNameEmployeeCount == size) {
System.out.println("All employees name are not nulls or nulls");
} else {
throw new EmployeesNotPassException();
}
}
And
public class EmployeesNotPassException extends RuntimeException {}
public class Pass {
public static void main(String[] args) {
List<Employee> list = new ArrayList<>();
boolean res = true;
for (Employee e : list) {
res = res && isPass(e);
}
System.out.println(res);
}
public static boolean isPass(Employee employee) {
if (employee == null)
return false;
if (employee.getName() == null)
return true;
if (employee.getName() != null && !StringUtils.isEmpty(employee.getName())) {
return true;
}
return false;
}
}

Comparing tree structures of haystack and needle

I want to write a method that would record all positions of nodes of haystack starting from where the pattern (structure) of itself matches as that of the needle. The value stored in the node doesn't need to be equal, its just the pattern that is supposed to match.
Illustration
Example 1
If I have the following haystack and needle
In the example above, the program is expected to record
ROOT
ROOT->Left
Example 2
If I have the same haystack as that of above and my needle as
Then my program is expected to record,
ROOT
ROOT->Left
ROOT->Right
However, it seems like the way I am implementing my code is flawed because my method even records positions that shouldn't have been true.
The way I am implementing my code is, I have the following method that would return a list which contains all such positions and I am using a isSubtree method to check if the pattern starting from a particular node finds a match.
public static List<String> searchForNeedleInHaystack(Node haystack,
Node needle) {
List<String> resultList = new ArrayList<String>();
if(haystack.getLeftChild() != null) {
value = value + "L";//value is just a global string variable initially ""
if(isSubtree(haystack.getLeftChild(), needle)) {
resultList.add(value);
} else {
if(value.length() > 1)
value = value.substring(0, value.length() - 1);
}
searchForNeedleInHaystack(haystack.getLeftChild(), needle);
}
if(haystack.getRightChild() != null) {
value = value + "R";
if(isSubtree(haystack.getRightChild(), needle)) {
resultList.add(value);
} else {
if(value.length() > 1)
value = value.substring(0, value.length() - 1);
}
searchForNeedleInHaystack(haystack.getRightChild(), needle);
}
return resultList;
}
public static boolean isSubtree(Node haystack, Node needle) {
if(needle == null)
return true;
if(haystack == null)
return false;
return isSubtree(haystack.getLeftChild(), needle.getLeftChild()) && isSubtree(haystack.getRightChild(), needle.getRightChild());
}
Node class
public class Node {
private String info;
private Node leftChild = null;
private Node rightChild = null;
public Node() {
this("");
}
public Node(String info) {
this.info = info;
}
public void setinfo(String info) {
this.info = info;
}
public void setLeftChild(Node n) {
leftChild = n;
}
public void setRightChild(Node n) {
rightChild = n;
}
public Node getLeftChild() {
return leftChild;
}
public Node getRightChild() {
return rightChild;
}
public String getinfo() {
return info;
}
public boolean isLeaf() {
return rightChild == null && leftChild == null;
}
}
Problem
I just wanted to know what logic could I perhaps use so that I can compare for subtree structures successfully?
Thanks in advance!

Remove at index function removes all elements before index

I use this remove method to remove the 3rd element of list. But it removes all the elements before the specified index. So if Jhon, Sam, Philip, Emma are the list elements, if I remove 3rd element, the only remaining element is Nick. How can I fix this?
import java.util.*;
class List {
Customer listPtr;
int index;
public void add(Customer customer) {
Customer temp = customer;
if (listPtr == null) {
listPtr = temp;
index++;
} else {
Customer x = listPtr;
while (x.next != null) {
x = x.next;
}
x.next = temp;
index++;
}
}
public void remove(int index) {
int size = size();
Customer tmp = listPtr, tmp2;
int i = 0;
while (i != size) {
if ((i + 1) == index) {
tmp2 = tmp;
listPtr = tmp2.next;
break;
}
tmp = tmp.next;
++i;
}
}
public int size() {
int size = 0;
Customer temp = listPtr;
while (temp != null) {
temp = temp.next;
size++;
}
return size;
}
public void printList() {
Customer temp = listPtr;
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
}
class DemoList {
public static void main(String args[]) {
List list = new List();
Customer c1 = new Customer("10011", "Jhon");
Customer c2 = new Customer("10012", "Sam");
Customer c3 = new Customer("10013", "Philip");
Customer c4 = new Customer("10014", "Emma");
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
list.remove(3);
System.out.println(list.size());
list.printList();
}
}
class Customer {
String id;
String name;
Customer next;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return id + " : " + name;
}
public boolean equals(Object ob) {
Customer c = (Customer) ob;
return this.id.equals(c.id);
}
}
There are several problems with the remove() method.
First of all, you should only be changing listPtr if index == 0.
In all other cases, you need to adjust node.next of the node at position index - 1.
P.S. Having index as a data member of List looks like an accident waiting to happen.
public void remove(int index) {
if (i == 0) {
// TODO: do some checks (listPtr is set, has next...)
listPtr = listPtr.next;
}
else {
int currentIndex = 0;
Customer currentElement = listPtr;
while (currentIndex != size()) {
if ((currentIndex + 1) == index) {
currentElement.next = currentElement.next.next;
break;
}
currentElement = currentElement.next;
currentIndex++;
}
}
}

Regarding Map as user defined base

I have developed a pojo named Employee.java. Now I was planning to make it as user defined collection. I want to make a map and store all the employee type objects in it.
Below is my pojo
public class Employee {
String name,job;
int salary;
public Employee(String n , String j, int t ) //constructor
{
this.name= n;
this.job=j;
this.salary= t;
}
#Override
public int hashCode()
{
return name.hashCode()+job.hashCode()+salary;
}
#Override
public boolean equals(Object obj) {
Employee e = (Employee) obj;
return this.name.equals(e.name)&&this.job.equals(e.job)&&this.salary==e.salary;
}
}
Now I have developed another class that contains map and will store employee type objects..
public static void main(String[] args)
{
Map employeeMap = new HashMap();
Employee e = new Employee("Saral", "Trainer", 34000);
Employee e1 = new Employee("Sarall", "saral", 34090);
employeeMap.put("S", e);
employeeMap.put("S1", e);
System.out.println(employeeMap.size());
Set s = employeeMap.entrySet();
Iterator it = s.iterator();
while(it.hasNext())
{
Map.Entry m =(Map.Entry)it.next();
System.out.println(m.getKey()+"\t"+m.getValue());
}
but when I try to run it , I want to fetch the employee details but I GET DISPLAYED THE OBJECT ON SCREEN ...I want to see the employees value, Please advise me how to get values from employee object.
2
S CollectionsPrac.Employee#285c2854
S1 CollectionsPrac.Employee#285c2854
You need to override the toString method in your Employee class, for example:
public String toString() {
return name + " [" + job + "] - salary: " + salary;
}
By the way, you can replace:
Iterator it = s.iterator();
while(it.hasNext())
{
Map.Entry m =(Map.Entry)it.next();
System.out.println(m.getKey()+"\t"+m.getValue());
}
with
System.out.println(s.toString());
Unless you really want the output to be tab separated.
You need to override the toString() method of Employee
#Override pulic String toString() {
return name + " " + job;
}
First of all. Your hashcode is broken.
Try running this:
System.out.println("Should be false: " + (new Employee("Sara", "Trainer", 1).hashCode() == new Employee("Trainer", "Sara", 1).hashCode()));
If you are using and IDE (like eclipse) there is a function to generate equals and hashcode methods automatically and you would get something like this:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((job == null) ? 0 : job.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + salary;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (job == null) {
if (other.job != null)
return false;
} else if (!job.equals(other.job))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (salary != other.salary)
return false;
return true;
}
As for your main method.. You should try to learn some basics about generics (the stuff inside the <>). You don't need the nity grity details at first. Just learn how to use it with lists and maps.. It will make your life a lot easier. Especially since your using and IDE...
Here is a refactored version of your main method:
public static void main(String[] args)
{
Map<String, Employee> employeeMap = new HashMap<String, Employee>();
Employee e = new Employee("Saral", "Trainer", 34000);
Employee e1 = new Employee("Sarall", "saral", 34090);
employeeMap.put("S", e);
employeeMap.put("S1", e1);
System.out.println(employeeMap.size());
Set<Entry<String, Employee>> entrySet = employeeMap.entrySet();
for (Entry<String, Employee> entry: entrySet) {
System.out.println(entry.getKey()+"\t"+entry.getValue().name);
}
System.out.println("Should be false: " + (new Employee("Sara", "Trainer", 1).hashCode() == new Employee("Trainer", "Sara", 1).hashCode()));
}
Change this in
Iterator it = s.iterator();
while(it.hasNext())
{
Map.Entry m =(Map.Entry)it.next();
Employee empl = (Employee) m.getValue();
System.out.println(m.getKey()+"\t"+empl.name);
}
As you can see with the line
Employee empl = (Employee) m.getValue();
the value is "casted" to an Employee object, and you can start to work with empl variable and use all the Employee class methods and members.

Categories

Resources