1

I'm currently reading up java's IO chapter regarding files and got me wondering what if, there are different data types in a text file, for example:

Position(in type String), ID(in type long), Name(in type String), Birthdate(dd/mm/yy in 3 type ints), title(Ms/Mr/Dr in type String), tasks done(in type int):

file name: employeeInfo.txt 


Manager, 987298347, Tesla, 03,04,1969, Mr, 4
Assistant, 290375020, Chris, 17,11,1989, Mr, 5
Manager, 99832482322, Steph, 11,02,1980, Ms, 4
Assistant, 679730283, Pete, 09,10,1980, Mr,7

How do I store them into two ArrayList that are grouped according to their position, in code? In order for me to do any flexible tasks, for example:

1. able to find out which employee achieve task done with more than 3
2. display employee's info when its ID is entered

Then the result may be as follows if 2 is invoked:

input:
290375020
output: 
Assistant, 290375020, Chris, 17/11/1989, Mr, 5

I hope there isn't any confusion caused. Thank you in advance

1
  • read the file and split the each line then convert each element to respective datatype and instead of arraylist you can use hashmap Commented Jul 3, 2020 at 5:59

3 Answers 3

2

I think it would be nice to create a class representing the data on a single line, parse each line into an instance of your class, and then compare the objects1.

Something like this:

List<Person> persons = new ArrayList<>();

for (String line : lines) { // Read the lines somehow

    String[] parts = line.split(", ");
    String position = parts[0];
    long id = Long.parseLong(parts[0]);
    // Et cetera

    persons.add(new Person(position, id, ...);
}

Then you can easily get all persons with tasks >= 3 in a for loop for example.

for (Person person : persons) {
    if (person.getTasks() >= 3) {
        // Print out the person
    }
}

By the way, a birthdate is best represented by a LocalDate. You can parse the date with

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd,MM,yyyy");
LocalDate dob = LocalDate.parse(parts[3], formatter);

Grouping

Grouping is often done using a Map. You could map each employee position to a list containing the employees with that position:

List<Person> personsFromFile = ...;
Map<String, List<Person>> map = new HashMap<>();
for (Person person : personsFromFile) {

    // If the position does not yet exist as key in the map, create it
    if (!map.containsKey(person.getPosition())) {
        map.put(person.getPosition(), new ArrayList<>());
    }

    // Get the list with for this position and add the current person to it
    map.get(person.getPosision()).add(person);
}

Or using Java Streams API:

personsFromFile.stream()
   .collect(Collectors.groupingBy(p -> p.getPosision()));

1 This is the whole point of object-oriented programming. We don't work with a bunch of variables, we model related data and functional classes and define functions operate on that object. Those are called methods. Each line in your file represents a person (or employee, you name it), so create a Person (or Employee) class.

Sign up to request clarification or add additional context in comments.

2 Comments

How do I group different position into a different ArrayList? For e.g., the Manager should belong to one ArrayList and the Assistant Should belong to another ArrayList. Therefore, I'm able to create a task for a different position.
@applePine Why do you want to maintain different ArrayLists? The best option depends on your usecase, but grouping is usually done through maps. See edit.
0

Think in rows (objects) rather than columns

Java is object-oriented, so use objects. Rather than track each column of data in your data file, write a class to represent each kind of data found in a row. Each value in the row goes into a named member field on the class.

As your read each row, instantiate an object of that class, and populate its values. Add each new object to a List as you work your way brought the input file.


Tip: In real work, use a CSV library to help with reading and parsing such a comma-separated values file. You have a choice of such libraries in Java. Personally, I use Apache Commons CSV.

Comments

0

For the employee class

class employee {
    private String position;
    private long ID;
    private String Name;
    private String dob;
    private String title;
    private int task_done;

    public employee(String position, long ID, String Name, String dob, String title, int task_done) {
        this.position = position;
        this.ID = ID;
        this.Name = Name;
        this.dob = dob;
        this.title = title;
        this.task_done = task_done;
    }

    public long getID(){
        return ID;
    }

    public int getTask() {
        return task_done;
    }
}

Main

public static void main(String[] args) throws IOException {
    List<employee> employees = new ArrayList<employee>();
    BufferedReader inFile = new BufferedReader(new FileReader("Filepath.txt"));
    String inputline;
    while ((inputline = inFile.readLine()) != null) {
        String[] data = inputline.split(", ");
        employees.add(new employee(data[0], Long.parseLong(data[1]), data[2], data[3], data[4], Integer.parseInt(data[5])));
    }
    inFile.close();
    for (employee em : employees) {
        if (em.getTask() >= 3) {
            System.out.println(em.getID());
        }
    }
}

The file: (I have remove the commas for the Birthdate)

Manager, 987298347, Tesla, 03/04/1969, Mr, 4
Assistant, 290375020, Chris, 17/11/1989, Mr, 5
Manager, 99832482322, Steph, 11/02/1980, Ms, 4
Assistant, 679730283, Pete, 09/10/1980, Mr, 7

The output:

987298347
290375020
99832482322
679730283

You can modify it to do flexible tasks.

2 Comments

Wow.. but if you remove the commas from the Birthdate. How do I treat the your birthdate as an object if I want to invoke it? for example, output employee's birthdate when the display employee's info
public String getDOB() { return dob; } . To display it, it was be the same as done for the ID.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.