Java: Combine 2 List <String []>

I have a row from a List. I want to create a new list (newList) by combining 2 lists. But it must meet these 3 conditions:

1) Copy the contents of store_inventory to newList.

2) Then, if the names of the items in the store_inventory and new_acquisitions files are the same, just add the two values ​​together and change them in newList.

3) If new_acquisitions has a new item that does not exist in store_inventory, add it to the new list.

The headers for the CSV list are: Element name, quantity, cost, price.

The list contains a string [] of name, quantity, cost and price for each row.

CSVReader from = new CSVReader(new FileReader("/test/new_acquisitions.csv")); List <String[]> acquisitions = from.readAll(); CSVReader to = new CSVReader(new FileReader("/test/store_inventory.csv")); List <String[]> inventory = to.readAll(); List <String[]> newList; 

Any code to get me started will be great! =]

that's what i still have ...

  for (int i = 0; i < acquisitions.size(); i++) { temp1 = acquisitions.get(i); for (int j = 1; j < inventory.size(); j++) { temp2 = inventory.get(j); if (temp1[0].equals(temp2[0])) { //if match found... do something? //break out of loop } } //if new item found... do something? } 
0
java string arrays list
source share
1 answer

I would start by creating a newList as a HashMap or TreeMap instead of List. This makes it easy to find the right entry. In addition, I would convert String [] to a custom object (e.g. Record) that contains a name, quantity, cost and price field. This will take care of copying the information. You can try something like this:

 Map<String, Record> newMap = new TreeMap<String, Record>(); for(String[] ss : acquisitions) { Record rec = Record.parse(ss); // For requirement (1) newMap.put(rec.getName(), rec); } for(String[] ss : inventory) { Record rec = Record.parse(ss); // For requirement (1) if(newMap.containsKey(rec.getName())) { // For requirement (2) // The mergeWith method can then add quantities together newMap.get(rec.getName()).mergeWith(rec); } else { // For requirement (3) newMap.put(rec.getName(), rec); } } 

change An additional advantage of having a recording object is that it can be printed on the screen much easier by implementing the toString function.

 public class Record implements Comparable<Record> { public static Record parse(String[] ss) { // TODO: implement some basic parsing } private String name; private int quantity; private BigDecimal cost, price; private Record() {} public String getName() { return name; } public int getQuantity() { return quantity; } public BigDecimal getCost() { return cost; } public BigDecimal getPrice() { return price; } public int compareTo(Record other) { return this.name.compareTo(other.name); } public String toString() { return name; } } 
+4
source share

All Articles