简体   繁体   中英

How to add different data types from text file into an arraylist?

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

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 objects 1 .

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM