vinothatub
BAN USER/**
* Print manager hierarchy from the file
*/
public static void printMgrHierarchy(File file){
if(file == null){
return;
}
BufferedReader br = null;
List<ManagerHierarchy> empList = new ArrayList<ManagerHierarchy>();
try {
br = new BufferedReader(new FileReader(file));
String line = br.readLine();
line = br.readLine();
int level = 0;
while(line != null){
if(line != null){
String[] tokens = line.split(" ");
if(tokens != null && tokens.length >= 3){
if(tokens[2].equalsIgnoreCase("null")){
level = 0;
}
try {
level = Integer.parseInt(tokens[2]);
} catch (NumberFormatException e) {
level = 0;
}
if(tokens[1] != null){
empList.add(new ManagerHierarchy(level, tokens[1]));
}
}
}
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
int count = 0;
Collections.sort(empList);
for(ManagerHierarchy itr : empList){
if(itr != null){
System.out.print(itr.getEmpName());
if(count+1 < empList.size()){
System.out.print(" | ");
}
}
count++;
}
}
class ManagerHierarchy implements Comparable<ManagerHierarchy>{
int mgrLevel;
String empName;
public ManagerHierarchy(int mgrLevel, String empName){
this.mgrLevel = mgrLevel;
this.empName = empName;
}
public int getLevel(){
return mgrLevel;
}
public String getEmpName(){
return empName;
}
@Override
public boolean equals(Object obj){
System.out.println("EQUALS");
if(!(obj instanceof ManagerHierarchy)){
return false;
}
if(this == obj){
return true;
}
return ((ManagerHierarchy) obj).getLevel() == this.mgrLevel;
}
@Override
public int hashCode(){
System.out.println("HASHCODE");
int out = 0;
out = out + 17 * this.mgrLevel;
return out;
}
@Override
public int compareTo(ManagerHierarchy o) {
if(this.mgrLevel == o.mgrLevel){
return 0;
}
else if(this.mgrLevel > o.mgrLevel){
return 1;
}
else{
return -1;
}
}
}
Here's a simple iterative solution (java) with comments for better understanding.
}
- vinothatub September 05, 2016