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










0














I am trying to convert an array that has three pieces of customer information in each 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.



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.










share|improve this question


























    0














    I am trying to convert an array that has three pieces of customer information in each 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.



    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.










    share|improve this question
























      0












      0








      0







      I am trying to convert an array that has three pieces of customer information in each 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.



      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.










      share|improve this question













      I am trying to convert an array that has three pieces of customer information in each 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.



      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.







      java






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 20:33









      William Loveless

      155




      155






















          7 Answers
          7






          active

          oldest

          votes


















          1














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





          share|improve this answer




























            1














            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:



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





            share|improve this answer




















            • This works for the first customer, but then the first name of the second customer in the array is "'." which is incorrect
              – William Loveless
              Nov 12 at 20:45










            • I don't follow...when I tried this I got customers array = [ jimmy , johnson, jjohnson@gmail.com, Joe, Donald, Joe_Donald@donald.org, ARTHUR, THOMPSON, ARTHUR@thompson.org]
              – Mike
              Nov 12 at 20:54


















            1














            Why do you need 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());






            share|improve this answer




























              0














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





              share|improve this answer




























                0














                I would start by overriding toString in Customer. You didn't post your version of Customer, but that might look like



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





                share|improve this answer




























                  0














                  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

                  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

                  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!






                  share|improve this answer




























                    0














                    I think your best bet here is to treat each element of your csv array as a distinct customer. 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());






                    share|improve this answer




















                      Your Answer






                      StackExchange.ifUsing("editor", function ()
                      StackExchange.using("externalEditor", function ()
                      StackExchange.using("snippets", function ()
                      StackExchange.snippets.init();
                      );
                      );
                      , "code-snippets");

                      StackExchange.ready(function()
                      var channelOptions =
                      tags: "".split(" "),
                      id: "1"
                      ;
                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                      StackExchange.using("externalEditor", function()
                      // Have to fire editor after snippets, if snippets enabled
                      if (StackExchange.settings.snippets.snippetsEnabled)
                      StackExchange.using("snippets", function()
                      createEditor();
                      );

                      else
                      createEditor();

                      );

                      function createEditor()
                      StackExchange.prepareEditor(
                      heartbeatType: 'answer',
                      autoActivateHeartbeat: false,
                      convertImagesToLinks: true,
                      noModals: true,
                      showLowRepImageUploadWarning: true,
                      reputationToPostImages: 10,
                      bindNavPrevention: true,
                      postfix: "",
                      imageUploader:
                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                      allowUrls: true
                      ,
                      onDemand: true,
                      discardSelector: ".discard-answer"
                      ,immediatelyShowMarkdownHelp:true
                      );



                      );













                      draft saved

                      draft discarded


















                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269689%2fconvert-string-array-with-3-pieces-of-information-into-an-array-of-objects-jav%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown

























                      7 Answers
                      7






                      active

                      oldest

                      votes








                      7 Answers
                      7






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      1














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





                      share|improve this answer

























                        1














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





                        share|improve this answer























                          1












                          1








                          1






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





                          share|improve this answer












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






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 12 at 20:44









                          Sand

                          1,108114




                          1,108114























                              1














                              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:



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





                              share|improve this answer




















                              • This works for the first customer, but then the first name of the second customer in the array is "'." which is incorrect
                                – William Loveless
                                Nov 12 at 20:45










                              • I don't follow...when I tried this I got customers array = [ jimmy , johnson, jjohnson@gmail.com, Joe, Donald, Joe_Donald@donald.org, ARTHUR, THOMPSON, ARTHUR@thompson.org]
                                – Mike
                                Nov 12 at 20:54















                              1














                              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:



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





                              share|improve this answer




















                              • This works for the first customer, but then the first name of the second customer in the array is "'." which is incorrect
                                – William Loveless
                                Nov 12 at 20:45










                              • I don't follow...when I tried this I got customers array = [ jimmy , johnson, jjohnson@gmail.com, Joe, Donald, Joe_Donald@donald.org, ARTHUR, THOMPSON, ARTHUR@thompson.org]
                                – Mike
                                Nov 12 at 20:54













                              1












                              1








                              1






                              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:



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





                              share|improve this answer












                              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:



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






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 12 at 20:38









                              Mike

                              1,278717




                              1,278717











                              • This works for the first customer, but then the first name of the second customer in the array is "'." which is incorrect
                                – William Loveless
                                Nov 12 at 20:45










                              • I don't follow...when I tried this I got customers array = [ jimmy , johnson, jjohnson@gmail.com, Joe, Donald, Joe_Donald@donald.org, ARTHUR, THOMPSON, ARTHUR@thompson.org]
                                – Mike
                                Nov 12 at 20:54
















                              • This works for the first customer, but then the first name of the second customer in the array is "'." which is incorrect
                                – William Loveless
                                Nov 12 at 20:45










                              • I don't follow...when I tried this I got customers array = [ jimmy , johnson, jjohnson@gmail.com, Joe, Donald, Joe_Donald@donald.org, ARTHUR, THOMPSON, ARTHUR@thompson.org]
                                – Mike
                                Nov 12 at 20:54















                              This works for the first customer, but then the first name of the second customer in the array is "'." which is incorrect
                              – William Loveless
                              Nov 12 at 20:45




                              This works for the first customer, but then the first name of the second customer in the array is "'." which is incorrect
                              – William Loveless
                              Nov 12 at 20:45












                              I don't follow...when I tried this I got customers array = [ jimmy , johnson, jjohnson@gmail.com, Joe, Donald, Joe_Donald@donald.org, ARTHUR, THOMPSON, ARTHUR@thompson.org]
                              – Mike
                              Nov 12 at 20:54




                              I don't follow...when I tried this I got customers array = [ jimmy , johnson, jjohnson@gmail.com, Joe, Donald, Joe_Donald@donald.org, ARTHUR, THOMPSON, ARTHUR@thompson.org]
                              – Mike
                              Nov 12 at 20:54











                              1














                              Why do you need 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());






                              share|improve this answer

























                                1














                                Why do you need 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());






                                share|improve this answer























                                  1












                                  1








                                  1






                                  Why do you need 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());






                                  share|improve this answer












                                  Why do you need 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());







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 12 at 20:45









                                  forpas

                                  8,3961419




                                  8,3961419





















                                      0














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





                                      share|improve this answer

























                                        0














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





                                        share|improve this answer























                                          0












                                          0








                                          0






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





                                          share|improve this answer












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






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Nov 12 at 20:44









                                          matt

                                          4,2441923




                                          4,2441923





















                                              0














                                              I would start by overriding toString in Customer. You didn't post your version of Customer, but that might look like



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





                                              share|improve this answer

























                                                0














                                                I would start by overriding toString in Customer. You didn't post your version of Customer, but that might look like



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





                                                share|improve this answer























                                                  0












                                                  0








                                                  0






                                                  I would start by overriding toString in Customer. You didn't post your version of Customer, but that might look like



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





                                                  share|improve this answer












                                                  I would start by overriding toString in Customer. You didn't post your version of Customer, but that might look like



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






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Nov 12 at 20:51









                                                  Elliott Frisch

                                                  152k1389178




                                                  152k1389178





















                                                      0














                                                      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

                                                      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

                                                      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!






                                                      share|improve this answer

























                                                        0














                                                        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

                                                        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

                                                        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!






                                                        share|improve this answer























                                                          0












                                                          0








                                                          0






                                                          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

                                                          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

                                                          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!






                                                          share|improve this answer












                                                          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

                                                          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

                                                          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!







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Nov 12 at 20:58









                                                          Jimmy

                                                          8,01135115200




                                                          8,01135115200





















                                                              0














                                                              I think your best bet here is to treat each element of your csv array as a distinct customer. 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());






                                                              share|improve this answer

























                                                                0














                                                                I think your best bet here is to treat each element of your csv array as a distinct customer. 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());






                                                                share|improve this answer























                                                                  0












                                                                  0








                                                                  0






                                                                  I think your best bet here is to treat each element of your csv array as a distinct customer. 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());






                                                                  share|improve this answer












                                                                  I think your best bet here is to treat each element of your csv array as a distinct customer. 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());







                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Nov 12 at 20:59









                                                                  Tom Drake

                                                                  42737




                                                                  42737



























                                                                      draft saved

                                                                      draft discarded
















































                                                                      Thanks for contributing an answer to Stack Overflow!


                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                      But avoid


                                                                      • Asking for help, clarification, or responding to other answers.

                                                                      • Making statements based on opinion; back them up with references or personal experience.

                                                                      To learn more, see our tips on writing great answers.





                                                                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                      Please pay close attention to the following guidance:


                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                      But avoid


                                                                      • Asking for help, clarification, or responding to other answers.

                                                                      • Making statements based on opinion; back them up with references or personal experience.

                                                                      To learn more, see our tips on writing great answers.




                                                                      draft saved


                                                                      draft discarded














                                                                      StackExchange.ready(
                                                                      function ()
                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269689%2fconvert-string-array-with-3-pieces-of-information-into-an-array-of-objects-jav%23new-answer', 'question_page');

                                                                      );

                                                                      Post as a guest















                                                                      Required, but never shown





















































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown

































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown







                                                                      Popular posts from this blog

                                                                      Top Tejano songwriter Luis Silva dead of heart attack at 64

                                                                      ReactJS Fetched API data displays live - need Data displayed static

                                                                      政党