简体   繁体   English

如何将文本文件中的不同数据类型添加到 arraylist 中?

[英]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:我目前正在阅读 java 的 IO 关于文件的章节,让我想知道如果文本文件中有不同的数据类型怎么办,例如:

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?如何将它们存储到两个 ArrayList 中,这些 Z57A97FE07FD492A8BE0EA6A760D683D6EZ 在代码中按其分组? 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 .我认为创建一个代表单行数据的 class 会很好,将每一行解析为 class 的实例,然后比较对象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 循环中获取所有任务 >= 3 的人。

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

By the way, a birthdate is best represented by a LocalDate .顺便说一句,生日最好用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 .分组通常使用Map完成。 You could map each employee position to a list containing the employees with that position:您可以 map 每个员工 position 到包含具有该 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:或使用 Java 流 API:

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

1 This is the whole point of object-oriented programming. 1这是面向对象编程的重点。 We don't work with a bunch of variables, we model related data and functional classes and define functions operate on that object.我们不使用一堆变量,我们 model 相关数据和功能类并定义函数在 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.文件中的每一行都代表一个人(或员工,您可以命名它),因此创建一个Person (或Employee )class。

Think in rows (objects) rather than columns考虑行(对象)而不是列

Java is object-oriented, so use objects. Java 是面向对象的,所以使用对象。 Rather than track each column of data in your data file, write a class to represent each kind of data found in a row .与其跟踪数据文件中的每一数据,不如编写一个 class 来表示在一行中找到的每种数据。 Each value in the row goes into a named member field on the class.行中的每个值都进入 class 上的命名成员字段。

As your read each row, instantiate an object of that class, and populate its values.在读取每一行时,实例化该 class 的 object,并填充其值。 Add each new object to a List as you work your way brought the input file.将每个新的 object 添加到List中,因为您按照自己的方式输入文件。


Tip: In real work, use a CSV library to help with reading and parsing such a comma-separated values file.提示:在实际工作中,使用 CSV 库来帮助读取和解析这样的逗号分隔值文件。 You have a choice of such libraries in Java.您可以在 Java 中选择此类库。 Personally, I use Apache Commons CSV .就个人而言,我使用Apache Commons CSV

For the employee class对于员工 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: output:

987298347
290375020
99832482322
679730283

You can modify it to do flexible tasks.您可以对其进行修改以执行灵活的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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