Search code examples
javatreemap

How Do I Return An Instance of the Current Class as a Value within a TreeMap?


I have to return an instance of the class I am in at the time, as one of the variables in a TreeMap which I am returning to main class. I can't seem to figure out how I am supposed to do this. This is my code as is, to show you what I mean to do:

public class Employee {
    public static Map<String,Employee> load() {
       String a="";
       String b="";
       String [] c;
       TreeMap<String, Employee> d=new TreeMap<>();
        try {
            Scanner in=new Scanner(new File("employees.txt"));
            while(in.hasNextLine()){
                c=in.nextLine().split("  ");
                a=c[0];
                b=c[1];
            }
//Naturally, the "b" below has a red quiggly line under it as this is a string
            d.put(a,b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
      return d;
    }
}

Solution

  • You need to actually construct an Employee using new. Something like:

    public class Employee {
        private final String name;
    
        public Employee(String name) {
            this.name = name;
        }
    
        public static Map<String,Employee> load() throws FileNotFoundException {
            TreeMap<String, Employee> map = new TreeMap<>();
            Scanner in = new Scanner(new File("employees.txt"));
            while(in.hasNextLine()) {
                String[] input = in.nextLine().split("  ");
                map.put(input[0], new Employee(input[1]));
            }
            return map;
        }
    }
    

    A better design would be to have your loading logic in a separate class. Using a few more recent Java features:

    record Employee(String name) { }
    
    public class EmployeeIndex {
        private final Map<String,Employee> index;
    
        public EmployeeIndex(String filename) {
            this.index = Files.lines(Paths.get(filename))
                .map(String::split)
                .collect(Collectors.toMap(a -> a[0], a -> new Employee(a[1]));
        }
    }