【问题标题】:How to add different data types from text file into an arraylist?如何将文本文件中的不同数据类型添加到数组列表中?
【发布时间】:2020-10-23 19:28:48
【问题描述】:

我目前正在阅读 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

如何在代码中将它们存储到两个根据位置分组的 ArrayList 中?为了让我做任何灵活的任务,例如:

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

我希望不会造成任何混乱。 提前谢谢你

【问题讨论】:

  • 读取文件并拆分每一行,然后将每个元素转换为相应的数据类型,而不是 arraylist,您可以使用 hashmap

标签: java file arraylist text


【解决方案1】:

我认为最好在一行上创建一个表示数据的类,将每一行解析为您的类的一个实例,然后比较对象1

类似这样的:

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, ...);
}

然后,例如,您可以在 for 循环中轻松获取所有任务 >= 3 的人。

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

顺便说一句,生日最好用LocalDate 表示。您可以使用

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

分组

通常使用Map 进行分组。您可以将每个员工职位映射到包含具有该职位的员工的列表:

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);
}

或使用 Java Streams API:

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

1 这是面向对象编程的重点。我们不使用一堆变量,我们对相关数据和功能类进行建模,并定义对那个对象进行操作的函数。这些被称为方法。文件中的每一行代表一个人(或员工,你可以命名它),所以创建一个Person(或Employee)类。

【讨论】:

  • 如何将不同的位置分组到不同的 ArrayList 中?例如,Manager 应该属于一个 ArrayList,而 Assistant 应该属于另一个 ArrayList。因此,我可以为不同的职位创建任务。
  • @applePine 为什么要维护不同的ArrayLists?最佳选择取决于您的用例,但分组通常通过地图完成。见编辑。
【解决方案2】:

考虑行(对象)而不是列

Java 是面向对象的,所以使用对象。与其跟踪数据文件中的每一 数据,不如编写一个类来表示在 中找到的每种数据。行中的每个值都进入类的命名成员字段。

当您阅读每一行时,实例化该类的一个对象,并填充其值。将每个新对象添加到 List,按照您的方式输入输入文件。


提示:在实际工作中,使用 CSV 库来帮助读取和解析这种逗号分隔值文件。您可以选择 Java 中的此类库。就个人而言,我使用 Apache Commons CSV

【讨论】:

    【解决方案3】:

    对于员工类

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

    主要

    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());
            }
        }
    }
    

    文件:(我删除了生日的逗号)

    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
    

    输出:

    987298347
    290375020
    99832482322
    679730283
    

    您可以对其进行修改以执行灵活的任务。

    【讨论】:

    • 哇.. 但是如果您从生日中删除逗号。如果我想调用它,如何将你的生日视为一个对象?例如显示员工信息时输出员工生日
    • public String getDOB() { return dob; } 。要显示它,它与 ID 相同。
    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多