简体   繁体   English

将包含3条信息的字符串数组转换为对象数组-JAVA

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

I am trying to convert an array that has three pieces of customer information in each bin: 我正在尝试转换一个在每个bin中具有三条客户信息的数组:

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

I have a class (Customers) that includes a constructor to make a customer with the first name, the last name, and an email. 我有一个(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());

This gets me almost to where I need to be, however there is one small problem-- when the information is being stored in the array, it does not consider the comma in the original array as one of the commas I am trying to use as a split. 这几乎使我到达了所需的位置,但是有一个小问题-当信息存储在数组中时,它不会将原始数组中的逗号视为我尝试使用的逗号之一分裂。 Here is what the code above gives me: 这是上面的代码给我的:

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

As you can see, the first bits of information is correct, but Joe (the first name of the second person) is lumped in with the first customer. 如您所见,信息的前几位是正确的,但是Joe(第二个人的名字)与第一位顾客在一起。

Calling 呼唤

customerList += csv[i];

will give you a String that looks like 会给你一个看起来像的字符串

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

There's probably multiple ways to fix it, but I would try adding a comma after you concatenate each entry from the csv array: 可能有多种方法可以修复它,但是在将csv数组中的每个条目连接起来后,我会尝试添加一个逗号:

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

Why do you need String customerList = ""; 为什么需要String customerList = ""; ? You can get the customs array like this: 您可以这样获取海关数组:

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

Using Streams? 使用流?

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

I think this was what you wanted to achieve, 我认为这就是您想要实现的目标,

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

I would start by overriding toString in Customer . 我将从覆盖Customer toString开始。 You didn't post your version of Customer , but that might look like 您没有发布您的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);
    }
}

Then you might use String.split and Arrays.stream and map your entries to Customer instances like 然后,您可以使用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);
}

And I get 我得到

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

Here's a suggestion for you, a couple of things to point out: 以下是对您的建议,需要指出以下几点:

  1. I'm using a List instead of an array, a list can grow dynamically and you don't need to specify the size up front, it's also a bit easier to work with than an array. 我使用的是列表而不是数组,列表可以动态增长,并且您不需要预先指定大小,并且比数组更容易使用。
  2. Use a foreach loop instead of standard for, you don't need the index so a foreach is perfect 使用foreach循环而不是标准循环,因为您不需要索引,所以foreach是完美的
  3. When splitting the line, just check you get the expected number of parts, perhaps treat the others as errors, so safeguard yourself later when you expect to find certain things in certain spots. 分割生产线时,只需检查您是否获得了预期的零件数量,也许将其他零件视为错误,因此在以后希望在某些地方发现某些东西时,请务必保护自己。
  4. The trim lets you get rid of whitespace, it's always good to clean the data as soon as you can so you don't get junk filtering through your application. 修剪使您摆脱空白,总是最好尽快清理数据,这样就不会通过应用程序进行垃圾筛选。
  5. Consider using Lombok , it gives you nice annotations to generate accessor methods, toString etc 考虑使用Lombok ,它为您提供了不错的注释来生成访问器方法,toString等

sample code: 样例代码:

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

This is the output I get, which I believe is what you're looking for 这是我得到的输出,我相信这就是您要寻找的输出

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

Good luck! 祝好运!

I think your best bet here is to treat each element of your csv array as a distinct customer. 我认为您最好的选择是将csv阵列的每个元素都视为不同的客户。 There's no need to concatenate them all into one big string. 无需将它们全部连接成一个大字符串。

    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