JP Morgan Interview Question for Java Developers


Country: India
Interview Type: Written Test




Comment hidden because of low score. Click to expand.
0
of 0 vote

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	
	static class Employee implements Comparator<Employee>
	{
		int _id;
		int mngr_id;
		String name;
		
		public Employee(int _id,String name,int mngr_id)
		{
			this._id = _id;
			this.mngr_id = mngr_id;
			this.name = name;
		}
		
		
		public int compare(Employee one,Employee two)
		{
			return (one.mngr_id - two.mngr_id);
		}
		
	}
	
	public static void arrangeHierarchy(String filename)
	{
		
		PriorityQueue<Employee> list = new PriorityQueue<Employee>();
		
		
	 			
		for (String line : Files.readAllLines(Paths.get(filename))) 
		{
			String[] parts = line.split("\\s+");
			int e_id = Integer.valueOf(parts[0]);
			String name = parts[1];
			int m_id = Integer.valueOf(parts[1]);
			
    		Employee e = new Employee(e_id,name,m_id);
    		list.add(e);
    		System.out.print(" "+m_id);
		}
		
	}
	
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		//C:/Users/jainh/employee.txt 
		arrangeHierarchy("C:/Users/jainh/employee.txt");
	}
	
}

- Himanshu Jain January 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Did you care to run the above ? what was the o/p ? looks like it will only print emp Ids.

- Vib January 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I tried this code online on ideone it doesn't have access to read files, But idea for this is same read each line of a file to make user defined objects and put them in a heap based on manager_id.

- Himanshu Jain January 04, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;
import java.nio.file.*;
import java.nio.charset.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	
	static class Employee implements Comparator<Employee>
	{
		int _id;
		int mngr_id;
		String name;
		
		public Employee(int _id,String name,int mngr_id)
		{
			this._id = _id;
			this.mngr_id = mngr_id;
			this.name = name;
		}
		
		
		public int compare(Employee one,Employee two)
		{
			return (one.mngr_id - two.mngr_id);
		}
		
	}
	
	public static void arrangeHierarchy(Path filepath)
	{
		
		PriorityQueue<Employee> list = new PriorityQueue<Employee>();
		try
		{
		String[] lines = (String[])Files.readAllLines(filepath,StandardCharsets.US_ASCII).toArray();
		
	 			
		for (String line : lines) 
		{
			String[] parts = line.split("\\s+");
			int e_id = Integer.valueOf(parts[0]);
			String name = parts[1];
			int m_id = Integer.valueOf(parts[1]);
			
    		Employee e = new Employee(e_id,name,m_id);
    		list.add(e);
    		System.out.println(" "+m_id);
		}
		}
		catch(IOException io)
		{
			System.out.println( " Exception : "+io);
		}
		
		//TODO: iterate over Employee priority queue to get hierarchy 
	}
	
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		//C:/Users/jainh/employee.txt 
		//Path file_path = new Path("C:/Users/jainh/employee.txt")
		Path employee_path = Paths.get("C:/Users/jainh/", "employee.txt");;
		arrangeHierarchy(employee_path);
	}
	
}

- Himanshu Jain January 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This solution will work with the assumption that manager's Id will always be
greater than the Employee's Id, which need not be the case, which clearly is not mentioned in the problem statement

- Phaneendra February 01, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void printContentinFormat(String fileName) throws IOException{
File f = new File(fileName);
if(f.exists()){
Map<Integer,String> empMgrMap = getMap(f);
Set<Entry<Integer,String>> entSet = empMgrMap.entrySet();
for(Entry<Integer,String> e : entSet){
System.out.print("|"+ e.getValue());
}
}
}
private Map<Integer,String> getMap(File f) throws IOException {
BufferedReader buff = null;
Map<Integer,String> empMgrMap = null;
try {
buff = new BufferedReader(new FileReader (f));
empMgrMap = new TreeMap<Integer,String>();
String s = buff.readLine();

while(( s = buff.readLine()) != null){
String[] parts = s.split("\"");
if(parts.length == 3){
parts[2] = parts[2].trim();
if(parts[2].equalsIgnoreCase("Null")){
parts[2] = "0";
}

int key = Integer.parseInt(parts[2].trim() );
String value = parts[1];

value = (empMgrMap.containsKey(key)? empMgrMap.get(key)+"|"+value +"|":value);
empMgrMap.put(key, value);
}}

} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (buff != null){
buff.close();
}
}
return empMgrMap;
}

- Anonymous January 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The problem is just to build the staff tree and print it as a directory?

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

public class CompanyTree {
	private static String levelPrefix = "    ";
	private HashMap<Integer, Employ> staff = new HashMap<Integer, Employ>();
	
	class Employ{
		private int id;
		private String name;
		private int superiorId;
		private Set<Integer> subordinateIds;
		
		public Employ(int id, String name, int superiorId){
			this.id = id;
			this.name = name;
			this.superiorId = superiorId;
			this.subordinateIds = null;
		}
		public int getId(){
			return id;
		}
		public String getName(){
			return name;
		}
		public int getSuperiorId(){
			return superiorId;
		}
		public void addSubordinate(int id){
			if(subordinateIds == null)
				subordinateIds = new HashSet<Integer>();
			subordinateIds.add(id);
		}
		public void showTeam(int level){
			for(int i = 0; i < level; ++i) System.out.print(levelPrefix);
			
			Employ e = staff.get(id);
			System.out.println(e.getName());
			
			if(subordinateIds != null){
				Iterator<Integer> iter = subordinateIds.iterator();
				while(iter.hasNext()){
					Integer ID = iter.next();
					staff.get(ID).showTeam(level + 1);
				}
			}
		}
	}
	
	private void setTeams(){
		Iterator<Entry<Integer, Employ>> iter = staff.entrySet().iterator();
		while(iter.hasNext()){
			Entry<Integer, Employ> entry = iter.next();
			Employ superior = staff.get(entry.getValue().getSuperiorId());
			if(superior != null) superior.addSubordinate(entry.getKey());
		}
	}
	public void addEmploy(int id, String name, int superiorId){
		staff.put(id, new Employ(id, name, superiorId));
	}
	public void show(){
		setTeams();
		
		Iterator<Entry<Integer, Employ>> iter = staff.entrySet().iterator();
		while(iter.hasNext()){
			Entry<Integer, Employ> entry = iter.next();
			Employ e = entry.getValue();
			if(e.getSuperiorId() == -1)	e.showTeam(0);
		}
	}
	
	public static void main(String[] args) throws IOException{
		String filePath = "input.txt";
		BufferedReader br = new BufferedReader(new FileReader(filePath));
		
		String line;
		CompanyTree company = new CompanyTree();
		while((line = br.readLine()) != null){
			String[] arr = line.split(" +");
			if(arr[2].equals("Null")) company.addEmploy(Integer.parseInt(arr[0]), arr[1], -1);
			else company.addEmploy(Integer.parseInt(arr[0]), arr[1], Integer.parseInt(arr[2]));
		}
		
		company.show();
	}
}

- uuuouou January 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Manager hierarchy can be implemented using tree data structure, and print the tree elements using level order tree traversal.

- iamcodeenthusiast January 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

- vinothatub January 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

There is a } missing in the main...

- tasse January 17, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args){
    Queue<String> q = readAndSortInputFile(new IDComparator());
    StringBuilder res = new StringBuilder();
    while (!q.isEmpty()) {
      res.append(q.peek().split(" ")[1].substring(1, q.peek().split(" ")[1].length() - 1) + (q.size() > 1 ? "|" : ""));
      q.poll();
    }
    System.out.print(res.toString());

private static Queue<String> readAndSortInputFile(Comparator comparator) {
    Queue<String> q = new PriorityQueue<>(comparator);
    try (Stream<String> lines = Files
        .lines(FileSystems.getDefault().getPath("src/input"), Charset.defaultCharset())) {
      for (String line : (Iterable<String>) lines.skip(1)::iterator) {
        q.add(line);
      }
    } catch (Exception e) {
      System.out.println(e);
    }
    return q;
  }
public class IDComparator implements Comparator<String> {
  @Override
  // el = i "XYZ" k, sort by k, if k is the same sort by "XYZ"
  public int compare(String a, String b){

    Integer k1, k2;
    k1 = k2 = null;
    try{
      k1 = Integer.parseInt(a.split(" ")[2]);
      k2 = Integer.parseInt(b.split(" ")[2]);
    }
    catch(Exception e){
    }
    if(k1 == null)
      return -1;
    if(k2 == null)
      return 1;
    if(k1 == k2){
      String x1 = a.split(" ")[1];
      String x2 = b.split(" ")[1];
      for(int i = 0; i < Math.min(x1.length(), x2.length()); i++){
        if(x1.charAt(i) > x2.charAt(i))
          return 1;
        else if (x1.charAt(i) < x2.charAt(i))
          return -1;
      }
      return x1.length() - x2.length();
    }
    else
      return k1 - k2;
  }
}

- tasse January 17, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.test.six;

import java.util.ArrayList;

public class Test8 {

	public static void main(String[] args) {

		ArrayList<Test88> input = new ArrayList<Test88>();
		ArrayList<Test88> output = new ArrayList<Test88>();

		input = initialize();
		output = processing(input);

		// print out 
		for (int i = 0; i < output.size(); i++) {
			System.out.print(output.get(i).name + " | ");
		}

	}

	private static ArrayList<Test88> processing(ArrayList<Test88> input) {
		ArrayList<Test88> retVal = new ArrayList<Test88>();
		int lowestNum = 10000;
		Test88 lowestObj = null;
		boolean nullFlag = false;
		for (int i = 0; i < input.size(); i++) {

			for (int j = 0; j < input.size(); j++) {

				// find lowest one first
				Test88 get88 = input.get(j);
				if (get88.flag != true) {

					// check Null
					if (get88.id != null) {

						// find lowest one
						if (get88.id < lowestNum) {
							lowestObj = get88;
							lowestNum = input.get(j).id;
						}
					} else { // if null
						retVal.add(get88);
						get88.flag = true;
						nullFlag = true;
						break;
					}
				}

			} // end of j
				// reset
			lowestNum = 10000;
			if (nullFlag == true) {
				nullFlag = false;
				continue;
			} else {
				retVal.add(lowestObj);
				lowestObj.flag = true;
			}
		}
		return retVal;

	}

	private static ArrayList<Test88> initialize() {
		ArrayList<Test88> retVal = new ArrayList<Test88>();
		for (int i = 0; i < 5; i++) {
			Test88 test88 = new Test88();
			test88.num = i;
			switch (i) {
			case 0:
				test88.name = "ABC";
				test88.id = 2;
				test88.flag = false;
				break;
			case 1:
				test88.name = "PRW";
				// test88.id = null;
				test88.flag = false;
				break;
			case 2:
				test88.name = "DEF";
				test88.id = 2;
				test88.flag = false;
				break;
			case 3:
				test88.name = "PRE";
				test88.id = 3;
				test88.flag = false;
				break;
			case 4:
				test88.name = "DKF";
				test88.id = 4;
				test88.flag = false;
				break;
			default:
				break;

			}
			retVal.add(test88);
		}
		return retVal;
	}

}

public class Test88 {
	int num;
	String name;
	Integer id;
	boolean flag;

}

- mannerh1 January 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.io.*;
class Employee{
private int empId;
private String managerName;
private int manId;

public int getEmpId(){
return this.empId;
}
public int getManId(){
return this.manId;
}
public String getManagerName(){
return this.managerName;
}
public void setEmpId(int eId){
this.empId=eId;
}
public void setManId(int mId){
this.manId=mId;
}
public void setManagerName(String name){
this.managerName=name;
}
public int hashcode(){
return this.empId;
}
public boolean equals(Employee o){
return this.empId==o.empId;
}

}
class compList implements Comparator<Employee>{
 
    @Override
public int compare(Employee e1,Employee e){

if(e1.getManId()==e.getManId())
{
return e1.getManagerName().compareTo(e.getManagerName());
}
else{
return e1.getManId()-e.getManId();
}
}
}
public class empSort{
public static void main(String [] args) throws IOException{
String filePath = "C:/Users/SR/Desktop/New folder (2)/input.txt";
		BufferedReader br = new BufferedReader(new FileReader(filePath));
		List<Employee> listEmp=new ArrayList<Employee>();
		String line;
		
		while((line = br.readLine()) != null){
		Employee emp = new Employee();
		
			String[] arr = line.split(";");
			
			emp.setEmpId(Integer.parseInt(arr[0]));
			emp.setManagerName(arr[1]);
			if(arr[2].equals("null")){
			emp.setManId(Integer.parseInt("0"));
			}
			else{
			emp.setManId(Integer.parseInt(arr[2]));
			}
			listEmp.add(emp);
} 
System.out.println("Before Sorting");
for(Employee em:listEmp){
System.out.println(em.getManId());
}
Collections.sort(listEmp,new compList());
System.out.println("After Sorting");
for(Employee e:listEmp){
            System.out.println(e.getEmpId()+":"+e.getManagerName()+":"+e.getManId());
        }
		
}
}

- Swatisha March 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

public class ReadFromFile {
public static void main(String[] args){
try{
Map<Integer,StringBuffer> map=new TreeMap<Integer, StringBuffer>();
HashMap<String, StringBuffer> mapNull=new HashMap<String, StringBuffer>();

File file=new File("C:\\Users\\mellary\\Desktop\\AngularJs\\DataBase.txt");
BufferedReader bufferedReader=new BufferedReader(new FileReader(file));
String line="";
while((line = bufferedReader.readLine())!=null){
String[] data=line.split(" ");
data[1]=data[1].replaceAll("\"", "");
try{
Integer mId=Integer.parseInt(data[data.length-1]);
if(map.containsKey(mId)){
StringBuffer mapVal=map.get(mId);
mapVal.append(data[1]+"@");
}else{
StringBuffer mapVal1=new StringBuffer();
mapVal1.append(data[1]+"@");
map.put(mId, mapVal1);
}
}catch(Exception e){
if((data[data.length-1]).equals("Null")){
StringBuffer mapVal2=new StringBuffer();
mapVal2.append(data[1]+"@");
mapNull.put(data[data.length-1], mapVal2);
}
}
}
printAllData(mapNull,map);
}catch(Exception e){
e.printStackTrace();
}
}
private static void printAllData(HashMap<String, StringBuffer> mapNull,
Map<Integer, StringBuffer> map) {
for(String s:mapNull.keySet()){

String[] data=mapNull.get(s).toString().split("@");
for(String dataIs:data){
System.out.println(s+"|"+dataIs);
}
}
for(int s:map.keySet()){

String[] data=map.get(s).toString().split("@");
for(String dataIs:data){
System.out.println(s+"|"+dataIs);
}
}
}
}

- Manoj April 16, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

public class ReadFromFile {
	public static void main(String[] args){
		try{
			Map<Integer,StringBuffer> map=new TreeMap<Integer, StringBuffer>();
			HashMap<String, StringBuffer> mapNull=new HashMap<String, StringBuffer>();
			
			File file=new File("C:\\Users\\mellary\\Desktop\\AngularJs\\DataBase.txt");
			BufferedReader bufferedReader=new BufferedReader(new FileReader(file));
			String line="";
			while((line = bufferedReader.readLine())!=null){
				String[] data=line.split(" ");
				data[1]=data[1].replaceAll("\"", "");
				try{
					Integer mId=Integer.parseInt(data[data.length-1]);
					if(map.containsKey(mId)){
						StringBuffer mapVal=map.get(mId);
						mapVal.append(data[1]+"@");
					}else{
						StringBuffer mapVal1=new StringBuffer();
						mapVal1.append(data[1]+"@");
						map.put(mId, mapVal1);
					}
				}catch(Exception e){
					if((data[data.length-1]).equals("Null")){
						StringBuffer mapVal2=new StringBuffer();
						mapVal2.append(data[1]+"@");
						mapNull.put(data[data.length-1], mapVal2);
					}
				}
			}
			printAllData(mapNull,map);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	private static void printAllData(HashMap<String, StringBuffer> mapNull,
			Map<Integer, StringBuffer> map) {
		for(String s:mapNull.keySet()){
			
			String[] data=mapNull.get(s).toString().split("@");
			for(String dataIs:data){
				System.out.println(s+"|"+dataIs);
			}
		}
		for(int s:map.keySet()){
			
			String[] data=map.get(s).toString().split("@");
			for(String dataIs:data){
				System.out.println(s+"|"+dataIs);
			}
		}
	}

}

- Manoj April 16, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.springapp.mvc;

import java.io.*;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: pramodd
 * Date: 5/15/15
 * Time: 10:19 PM
 * To change this template use File | Settings | File Templates.
 */
public class FileReader {
    Map<Integer, Employee> employees;
    Employee topEmployee;


    class Employee {
        int id;
        int mgrId;
        String empName;
        List<Employee> subordinates;
        public Employee(String id, String mgrid, String empName) {
            try {
                int empId = Integer.parseInt(id);
                int mgrId = 0;
                if (!"Null".equals(mgrid)) {
                    mgrId = Integer.parseInt(mgrid);
                }
                this.id = empId;
                this.mgrId = mgrId;
                this.empName = empName;
            } catch (Exception e) {
                System.out.println("Unable to create Employee as the data is " + id + " " + mgrid + " " + empName);
            }
        }

        List<Employee> getSubordinates() {
            return subordinates;
        }
        void setSubordinates(List<Employee> subordinates) {
            this.subordinates = subordinates;
        }
        int getId() {
            return id;
        }

        void setId(int id) {
            this.id = id;
        }

        int getMgrId() {
            return mgrId;
        }

    }

    public static void main(String[] args) throws IOException {
        FileReader thisClass = new FileReader();
        thisClass.process();
    }

    private void process() throws IOException {
        employees = new HashMap<Integer, Employee>();
        readDataAndCreateEmployees();
        buildHierarchy(topEmployee);
        printSubOrdinates(topEmployee, tabLevel);
    }

    private void readDataAndCreateEmployees() throws IOException {
        BufferedReader reader = new BufferedReader(new java.io.FileReader("src/main/java/com/springapp/mvc/input.txt"));
        String line = reader.readLine();
        while (line != null) {
            Employee employee = createEmployee(line);
            employees.put(employee.getId(), employee);
            if (employee.getMgrId() == 0) {
                topEmployee = employee;
            }
            line = reader.readLine();
        }
    }

    int tabLevel = 0;

    private void printSubOrdinates(Employee topEmployee, int tabLevel) {
        for (int i = 0; i < tabLevel; i++) {
            System.out.print("\t");
        }
        System.out.println("-" + topEmployee.empName);
        List<Employee> subordinates = topEmployee.getSubordinates();
        System.out.print(" ");
        for (Employee e : subordinates) {
            printSubOrdinates(e, tabLevel+1);
        }
    }
    public List<Employee> findAllEmployeesByMgrId(int mgrid) {
        List<Employee> sameMgrEmployees = new ArrayList<Employee>();
        for (Employee e : employees.values()) {
            if (e.getMgrId() == mgrid) {
                sameMgrEmployees.add(e);
            }
        }
        return sameMgrEmployees;
    }

    private void buildHierarchy(Employee topEmployee) {
        Employee employee = topEmployee;
        List<Employee> employees1 = findAllEmployeesByMgrId(employee.getId());
        employee.setSubordinates(employees1);
        if (employees1.size() == 0) {
            return;
        }

        for (Employee e : employees1) {
            buildHierarchy(e);
        }
    }

    private Employee createEmployee(String line) {
        String[] values = line.split(" ");
        Employee employee = null;
        try {
            if (values.length > 1) {
                employee = new Employee(values[0], values[2], values[1]);
            }
        } catch (Exception e) {
            System.out.println("Unable to create Employee as the data is " + values);
        }
        return employee;
    }
}

- Pramod May 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.springapp.mvc;

import java.io.*;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: pramodd
 * Date: 5/15/15
 * Time: 10:19 PM
 * To change this template use File | Settings | File Templates.
 */
public class FileReader {
    Map<Integer, Employee> employees;
    Employee topEmployee;


    class Employee {
        int id;
        int mgrId;
        String empName;
        List<Employee> subordinates;
        public Employee(String id, String mgrid, String empName) {
            try {
                int empId = Integer.parseInt(id);
                int mgrId = 0;
                if (!"Null".equals(mgrid)) {
                    mgrId = Integer.parseInt(mgrid);
                }
                this.id = empId;
                this.mgrId = mgrId;
                this.empName = empName;
            } catch (Exception e) {
                System.out.println("Unable to create Employee as the data is " + id + " " + mgrid + " " + empName);
            }
        }

        List<Employee> getSubordinates() {
            return subordinates;
        }
        void setSubordinates(List<Employee> subordinates) {
            this.subordinates = subordinates;
        }
        int getId() {
            return id;
        }

        void setId(int id) {
            this.id = id;
        }

        int getMgrId() {
            return mgrId;
        }

    }

    public static void main(String[] args) throws IOException {
        FileReader thisClass = new FileReader();
        thisClass.process();
    }

    private void process() throws IOException {
        employees = new HashMap<Integer, Employee>();
        readDataAndCreateEmployees();
        buildHierarchy(topEmployee);
        printSubOrdinates(topEmployee, tabLevel);
    }

    private void readDataAndCreateEmployees() throws IOException {
        BufferedReader reader = new BufferedReader(new java.io.FileReader("src/main/java/com/springapp/mvc/input.txt"));
        String line = reader.readLine();
        while (line != null) {
            Employee employee = createEmployee(line);
            employees.put(employee.getId(), employee);
            if (employee.getMgrId() == 0) {
                topEmployee = employee;
            }
            line = reader.readLine();
        }
    }

    int tabLevel = 0;

    private void printSubOrdinates(Employee topEmployee, int tabLevel) {
        for (int i = 0; i < tabLevel; i++) {
            System.out.print("\t");
        }
        System.out.println("-" + topEmployee.empName);
        List<Employee> subordinates = topEmployee.getSubordinates();
        System.out.print(" ");
        for (Employee e : subordinates) {
            printSubOrdinates(e, tabLevel+1);
        }
    }
    public List<Employee> findAllEmployeesByMgrId(int mgrid) {
        List<Employee> sameMgrEmployees = new ArrayList<Employee>();
        for (Employee e : employees.values()) {
            if (e.getMgrId() == mgrid) {
                sameMgrEmployees.add(e);
            }
        }
        return sameMgrEmployees;
    }

    private void buildHierarchy(Employee topEmployee) {
        Employee employee = topEmployee;
        List<Employee> employees1 = findAllEmployeesByMgrId(employee.getId());
        employee.setSubordinates(employees1);
        if (employees1.size() == 0) {
            return;
        }

        for (Employee e : employees1) {
            buildHierarchy(e);
        }
    }

    private Employee createEmployee(String line) {
        String[] values = line.split(" ");
        Employee employee = null;
        try {
            if (values.length > 1) {
                employee = new Employee(values[0], values[2], values[1]);
            }
        } catch (Exception e) {
            System.out.println("Unable to create Employee as the data is " + values);
        }
        return employee;
    }
}

- Pramod May 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

TreeMap<String, String> map = new TreeMap<String, String>();
    //replace null by 0, key = managerid+id
    map.put("2" + "1", "ABC");
    map.put("0"+"2", "PRW");
    map.put("2"+"3", "DEF");
    map.put("3"+"4", "PRE");
    map.put("4"+"5", "DKF");
    
    for(Entry<String, String> ent : map.entrySet()){
      System.out.println(ent.getValue());
    }

- mitu July 08, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

TreeMap<String, String> map = new TreeMap<String, String>();
//replace null by 0, key = managerid+id
map.put("2" + "1", "ABC");
map.put("0"+"2", "PRW");
map.put("2"+"3", "DEF");
map.put("3"+"4", "PRE");
map.put("4"+"5", "DKF");

for(Entry<String, String> ent : map.entrySet()){
System.out.println(ent.getValue());
}

- Anonymous July 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

package samples;

import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;

class MySoultion
{
static Map map = new TreeMap();
private static String[] parse(String line) {
StringTokenizer st = new StringTokenizer(line, " ");
String[] parts = new String[st.countTokens()];
int count = 0;
while(st.hasMoreElements()) {
parts[count] = st.nextToken();
count++;
}
return parts;
}
public static void arrangeHierarchy()
{

String currentLine;

BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("G:\\EclipseWorkspace\\samples\\src\\samples\\employee.txt")));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
while((currentLine = br.readLine()) != null){
String[] data = parse(currentLine);
if (data[2].equals("Null"))
data[2] = "0";
Integer key =Integer.valueOf(data[2]);
if (map.containsKey(key))
key += 1;
map.put(key, data[1]);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main (String[] args) throws java.lang.Exception
{
arrangeHierarchy();
String result = "";
Set keys = map.keySet();
Iterator it = keys.iterator();
while(it.hasNext()) {
result += (String)(map.get(it.next()));
result += "|";
}
result = result.substring(0, result.length()-1);
result = result.replace("\"", "");
System.out.println(result);
}

}

- Hemanth Kumar July 10, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

package samples;

import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;

class MySoultion
{
static Map map = new TreeMap();
private static String[] parse(String line) {
StringTokenizer st = new StringTokenizer(line, " ");
String[] parts = new String[st.countTokens()];
int count = 0;
while(st.hasMoreElements()) {
parts[count] = st.nextToken();
count++;
}
return parts;
}
public static void arrangeHierarchy()
{

String currentLine;

BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("G:\\EclipseWorkspace\\samples\\src\\samples\\employee.txt")));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
while((currentLine = br.readLine()) != null){
String[] data = parse(currentLine);
if (data[2].equals("Null"))
data[2] = "0";
Integer key =Integer.valueOf(data[2]);
if (map.containsKey(key))
key += 1;
map.put(key, data[1]);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main (String[] args) throws java.lang.Exception
{
arrangeHierarchy();
String result = "";
Set keys = map.keySet();
Iterator it = keys.iterator();
while(it.hasNext()) {
result += (String)(map.get(it.next()));
result += "|";
}
result = result.substring(0, result.length()-1);
result = result.replace("\"", "");
System.out.println(result);
}

}

- Hemanth Kumar July 10, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

//We will use a tree map
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class EmployeeHierarchy {

/* Key = Manager ID
* Value = List of Employees under the manager
*/
static Map<Integer, List<String>> employeeMap = new TreeMap<Integer, List<String>>();

public static void main(String[] args)throws Exception {
populateEmployeeHierarchyMap();
//Getting all manager ID's
Iterator<Integer> it = employeeMap.keySet().iterator();

while(it.hasNext()){
Integer i = it.next();
List<String> list = employeeMap.get(i);
Iterator<String> employees = list.iterator();
while(employees.hasNext()){
System.out.print(employees.next() +" ");
}
System.out.println("");
}
}

public static void populateEmployeeHierarchyMap()throws Exception{
File file = new File("EmployeeData.txt");
file.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(file));
String str;
List<String> temp;
int skipLine = 0;
while((str = br.readLine()) != null){
if(skipLine++ == 0)continue;
List<String> list = new ArrayList<String>();
String employeeData[] = str.split(" ");
if(employeeData[2] != null && !employeeData[2].equals("Null")){
//System.out.println(employeeData[2]);
Integer i = Integer.parseInt(employeeData[2]);
temp = employeeMap.get(i);
}else{
temp = employeeMap.get(0);
}

if( temp == null){
Integer managerId;
if(employeeData[2] == null || employeeData[2].equals("Null")){
managerId = new Integer(0);
}else{
managerId = new Integer(employeeData[2]);
}
list.add(employeeData[1]);
employeeMap.put(managerId,list);
}else{
temp.add(employeeData[1]);
}
}
}
}

- Infinite Possibilities August 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Same question repeated for me. Unfortunate did not notice this post :(

- cskandakumar143 September 12, 2015 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More