You are on the right track. The important thing is to split twice - once for the products, and once for the individual attributes.
Firstly, create a class which defines each product. I've taken a guess at what the fields mean in this example:
class Product {
String id;
String name;
String price;
}
Now you can read in the file and build instances of a product from the fields.
// Read the entire file
String text = new String(Files.readAllBytes(Paths.get("D:/input.txt")), StandardCharsets.UTF_8);
// Split into an array of strings, representing products
String[] prodStr = text.split(";");
// Create a list of product objects, currently empty
List<Product> prodList = new ArrayList<>();
// Loop over each product string
for (String pr : prodStr) {
// Split this string into separate fields
String[] fields = pr.split(":");
// Build a product object from the fields
Product product = new Product();
product.id = fields[0];
product.name = fields[1];
product.price = fields[2];
// Add this product to the list
prodList.add(product);
}
// Print all the products to see what we get
System.out.println(prodList);
I added a toString()
method to the Product class, and running this code with your example data gives:
[Product{id='4462', name='Coca-Cola 2L Bottle', price='1.69'}, Product{id='4980', name='Andrex 4 Pack', price='1.99'}, Product{id='2620', name='Haribo Strawbs 80g', price='0.50'}, Product{id='3223', name='Pedigree in gravy (with Chicken)', price='0.75'}]
To differentiate between products, implement hashCode()
and equals()
. e.g. A very simplistic solution could be:
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object o) {
Product product = (Product) o;
return id.equals(product.id);
}