簡體   English   中英

如何將文本文件中的不同數據類型添加到 arraylist 中?

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

我目前正在閱讀 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 中,這些 Z57A97FE07FD492A8BE0EA6A760D683D6EZ 在代碼中按其分組? 為了讓我做任何靈活的任務,例如:

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

我希望不會造成任何混亂。 先感謝您

我認為創建一個代表單行數據的 class 會很好,將每一行解析為 class 的實例,然后比較對象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完成。 您可以 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);
}

或使用 Java 流 API:

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

1這是面向對象編程的重點。 我們不使用一堆變量,我們 model 相關數據和功能類並定義函數在 object 上運行。 這些被稱為方法。 文件中的每一行都代表一個人(或員工,您可以命名它),因此創建一個Person (或Employee )class。

考慮行(對象)而不是列

Java 是面向對象的,所以使用對象。 與其跟蹤數據文件中的每一數據,不如編寫一個 class 來表示在一行中找到的每種數據。 行中的每個值都進入 class 上的命名成員字段。

在讀取每一行時,實例化該 class 的 object,並填充其值。 將每個新的 object 添加到List中,因為您按照自己的方式輸入文件。


提示:在實際工作中,使用 CSV 庫來幫助讀取和解析這樣的逗號分隔值文件。 您可以在 Java 中選擇此類庫。 就個人而言,我使用Apache Commons CSV

對於員工 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;
    }
}

主要的

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

output:

987298347
290375020
99832482322
679730283

您可以對其進行修改以執行靈活的任務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM