这是我的csv文件:
AP1234,Apple,iPhone5s,229.5,64,
AP6261,Apple,iPhone7,323.5,64,
SM9829,Samsung,GalaxyS7,555.0,64,
SM9230,Samsung,GalaxyS8,444.0,64,
SSSSS,Huawei,99C,1100.0,64,
从左到右:
Serial Number, Brand, Model, Price, Memory
可以说我要删除三星的所有电话,该怎么办?
到目前为止我的代码
//Get phone by make
public Phone getPhoneByMake(String make)
{
for(Phone p : this.PhoneList) {
if(p.getMake().equals(make))
return p;
}
return null;
}
//Delete all phones of certain make
public void deleteAllMake(Phone p) {
if(p == null)
throw new IllegalArgumentException("Phone argument is null");
PhoneList.remove(p);
}
和主要
try {
Phone pl = pMgr.getPhoneByMake("Samsung");
pMgr.deleteAllMake(pl);
}catch (IllegalArgumentException exc) {
}
答案 0 :(得分:1)
如果要从csv文件中删除所有特定型号,则可以从文件中读取所有电话,过滤电话并写回。下面的最小示例:
public static void main(String[] args) {
List<Phone> phones = readPhonesFromCSV("fileName.csv");
String brandToDelete = "Samsung";
List<Phone> filteredPhones = phones.stream()
.filter(phone -> !phone.getBrand().equals(brandToDelete))
.collect(Collectors.toList());
writePhonesToCSV(filteredPhones);
}
public static List<Phone> readPhonesFromCSV(String fileName) {
// Read logic...
}
public static void writePhonesToCSV(List<Phone> phones) {
// Write logic...
}
答案 1 :(得分:0)
您可以只使用Collection.removeIf()
删除所有符合给定条件的对象:
String make = "Huawei";
phones.removeIf(p -> p.getMake().equals(make));
这将从列表中将所有具有华为作为make
属性的电话删除。