簡體   English   中英

將包含3條信息的字符串數組轉換為對象數組-JAVA

[英]Convert string array with 3 pieces of information into an array of objects - JAVA

我正在嘗試轉換一個在每個bin中具有三條客戶信息的數組:

    String[] csv = {"   jimmy   ,johnson,jjohnson@gmail.com",
               "Joe,Donald,Joe_Donald@donald.org",
               "ARTHUR,THOMPSON,ARTHUR@thompson.org"};

我有一個(Customers)類,其中包含一個構造函數,該構造函數使用名字,姓氏和電子郵件來創建客戶。

String customerList = "";
    for (int i = 0; i < csv.length; i++) {
        customerList += csv[i];
    }

    String[] customers = customerList.split(",");

    Customer[] customs = new Customer[(customers.length / 3)];

    for (int i = 0; i < customers.length / 3; i += 3) {
        customs[i] = new Customer(customers[i], customers[i + 1], customers[i + 2]);
    }

    System.out.println(customs[0].getFirst_name());
    System.out.println(customs[0].getLast_name());
    System.out.println(customs[0].getEmail());

這幾乎使我到達了所需的位置,但是有一個小問題-當信息存儲在數組中時,它不會將原始數組中的逗號視為我嘗試使用的逗號之一分裂。 這是上面的代碼給我的:

Email Creator
=========================
   jimmy   
johnson
jjohnson@gmail.comJoe

如您所見,信息的前幾位是正確的,但是Joe(第二個人的名字)與第一位顧客在一起。

呼喚

customerList += csv[i];

會給你一個看起來像的字符串

   jimmy   ,johnson,jjohnson@gmail.comJoe,Donald,Joe_Donald@donald.orgARTHUR,THOMPSON,ARTHUR@thompson.org

可能有多種方法可以修復它,但是在將csv數組中的每個條目連接起來后,我會嘗試添加一個逗號:

customerList += csv[i] + ",";

為什么需要String customerList = ""; 您可以這樣獲取海關數組:

String[] csv = {"   jimmy   ,johnson,jjohnson@gmail.com",
        "Joe,Donald,Joe_Donald@donald.org",
        "ARTHUR,THOMPSON,ARTHUR@thompson.org"};

Customer[] customs = new Customer[csv.length];

for (int i = 0; i < csv.length; i++) {
    String[] splitted = csv[i].split(",");
    customs[i] = new Customer(splitted[0].trim(), splitted[1].trim(), splitted[2].trim());
}

使用流?

List<Customer> customer = Arrays.stream(customerList).map( 
        s->{
            String[] items = s.split(",");
            return new Customer(items[0], items[1], items[2]);
        }     
    }.collect(Collectors.toList());

我認為這就是您想要實現的目標,

String[] csv = {"   jimmy   ,johnson,jjohnson@gmail.com",
        "Joe,Donald,Joe_Donald@donald.org",
        "ARTHUR,THOMPSON,ARTHUR@thompson.org"};

Customer[] customs = new Customer[csv.length];

for (int i = 0; i < csv.length ; i++) {
    String[] customerDetails = csv[i].split(",");
    customs[i] = new Customer(customerDetails[0].trim(), customerDetails[1].trim(), customerDetails[2].trim());
}

System.out.println(customs[0].getFirst_name()));
System.out.println(customs[0].getLast_name());
System.out.println(customs[0].getEmail());

我將從覆蓋Customer toString開始。 您沒有發布您的Customer版本,但是看起來像

public class Customer {
    private String firstName;
    private String lastName;
    private String email;

    public Customer(String first, String last, String email) {
        this.firstName = first.trim();
        this.lastName = last.trim();
        this.email = email.trim();
    }

    @Override
    public String toString() {
        return String.format("first: %s, last: %s, email: %s", firstName, lastName, email);
    }
}

然后,您可以使用String.splitArrays.stream並將您的條目映射到Customer實例,例如

String[] csv = { "   jimmy   ,johnson,jjohnson@gmail.com", "Joe,Donald,Joe_Donald@donald.org",
        "ARTHUR,THOMPSON,ARTHUR@thompson.org" };
List<Customer> customs = Arrays.stream(csv).map(s -> s.split("\\s*,\\s*"))
        .map(t -> new Customer(t[0], t[1], t[2])).collect(Collectors.toList());
for (Customer c : customs) {
    System.out.println(c);
}

我得到

first: jimmy, last: johnson, email: jjohnson@gmail.com
first: Joe, last: Donald, email: Joe_Donald@donald.org
first: ARTHUR, last: THOMPSON, email: ARTHUR@thompson.org

以下是對您的建議,需要指出以下幾點:

  1. 我使用的是列表而不是數組,列表可以動態增長,並且您不需要預先指定大小,並且比數組更容易使用。
  2. 使用foreach循環而不是標准循環,因為您不需要索引,所以foreach是完美的
  3. 分割生產線時,只需檢查您是否獲得了預期的零件數量,也許將其他零件視為錯誤,因此在以后希望在某些地方發現某些東西時,請務必保護自己。
  4. 修剪使您擺脫空白,總是最好盡快清理數據,這樣就不會通過應用程序進行垃圾篩選。
  5. 考慮使用Lombok ,它為您提供了不錯的注釋來生成訪問器方法,toString等

樣例代碼:

public static void main(String[] args) throws IOException {
    String[] csv = {
        "   jimmy   ,johnson,jjohnson@gmail.com",
        "Joe,Donald,Joe_Donald@donald.org",
        "ARTHUR,THOMPSON,ARTHUR@thompson.org"
    };
        // use a List rather than array, so it can grow dynamically
        List<Customer> customers = new ArrayList<Customer>();

        for (String line : csv) {
            System.out.println("Processing line: " + line);

            String[] parts = line.split(",");
            if (parts.length != 3) {
                System.out.println("Expected to find 3 parts in the line, but got " + parts.length);
            }

            // construct the customer, notice the .trim() to remove any whitespace
            Customer customer = new Customer(parts[0].trim(), parts[1].trim(), parts[2].trim());
            customers.add(customer);
        }

        System.out.println("Printing out customer list:");
        // loop through the customers and print them out
        for (Customer c : customers) {
            System.out.println("firstName: " + c.firstName);
            System.out.println("lastName: " + c.lastName);
            System.out.println("email: " + c.email);
            System.out.println("\n");
        }
    }

    static class Customer {

        // accessors removed, consider using Lombok for @Data, @Getter, @Setter etc
        String firstName;
        String lastName;
        String email;

        public Customer(String firstName, String lastName, String email) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.email = email;
        }
    }

這是我得到的輸出,我相信這就是您要尋找的輸出

Processing line:    jimmy   ,johnson,jjohnson@gmail.com
Processing line: Joe,Donald,Joe_Donald@donald.org
Processing line: ARTHUR,THOMPSON,ARTHUR@thompson.org
Printing out customer list:
firstName: jimmy
lastName: johnson
email: jjohnson@gmail.com


firstName: Joe
lastName: Donald
email: Joe_Donald@donald.org


firstName: ARTHUR
lastName: THOMPSON
email: ARTHUR@thompson.org

祝好運!

我認為您最好的選擇是將csv陣列的每個元素都視為不同的客戶。 無需將它們全部連接成一個大字符串。

    String[] csv = {"   jimmy   ,johnson,jjohnson@gmail.com",
           "Joe,Donald,Joe_Donald@donald.org",
           "ARTHUR,THOMPSON,ARTHUR@thompson.org"};

    Customer[] customs = new Customer[csv.length];
    for (int cidx = 0; cidx < csv.length; cidx++) {
        String[] fields = csv[cidx].split(",");

        customs[cidx++] = new Customer(
                fields.length>0 ? fields[0].trim() : null, 
                fields.length>1? fields[1].trim() : null, 
                fields.length>2? fields[2].trim() : null);
    }
    for (Customer custom : customs) {
        System.out.println("first="+custom.getFirst_name() + ", last="+custom.getLast_name()+", email="+custom.getEmail());
    }

暫無
暫無

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

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