I am a newbie of c++. Now I am doing a project need to read a customer list from a csv file and then search if there is a username like "Ali" and printout all the data about Ali. How can I search "Ali" and printout all the data about Ali like CustomerNo , Name , PhoneNo and Status? And if there is multiple data with "Ali" , how can I printout all of them either? Here is my code:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Iterator; public class LoadCustomer { public static void main(String[] args) throws IOException{ System.out.println ("Load customer from file"); ArrayList<Customer> customers = readCustomerFromFile(); System.out.println (customers); System.out.println (); private static ArrayList<Customer> readCustomerFromFile() throws IOException{ ArrayList<Customer> customers = new ArrayList<>(); List<String> lines = Files.readAllLines(Paths.get("customer.csv")); for (int i = 1 ; i < lines.size() ; i++){ String[] items = lines.get(i).split(","); int customerNo = Integer.parseInt(items[0]); int phoneNo = Integer.parseInt(items[2]); customers.add (new Customer(customerNo,items[1],phoneNo,items[3])); } return customers; } } Here is my Customer class:(added getName getter)
public class Customer { private int customerNo; private String name; private int phoneNo; private String status; public Customer () {} public Customer (int customerNo, String name, int phoneNo, String status){ this.customerNo = customerNo; this.name = name; this.phoneNo = phoneNo; this.status = status; } public String getName(){ return name; } public String toString(){ return customerNo + " " + name + " " + phoneNo + " " + status; } public String toCSVString(){ return customerNo + "," + name + "," + phoneNo + "," + status; } } And here is my data:
CustomerNo Name PhoneNo Status 1 Ali 12345 Normal 2 Siti 23456 Normal 3 Rone 78910 Normal 4 Jean 56789 Normal 5 Roby 28573 Normal 6 Ali 78532 Normal Thank you very much for your attention. Edited : Here is my code for this program:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; public class FindCustomer { public static void main(String[] args) throws IOException{ System.out.println ("Load customer from file"); java.util.Map<String, List<Customer>> customers = Files.lines(Paths.get("customer.csv")) .map(line -> line.split(",")) .map(field -> new Customer( Integer.parseInt(field[0]), field[1], Integer.parseInt(field[2]), field[3])) .collect(Collectors .groupingBy(Customer::getName)); System.out.println (customers); } }
https://stackoverflow.com/questions/65582373/searching-data-from-arraylist January 06, 2021 at 12:03AM
没有评论:
发表评论