我有一个帐户的ArrayList。带有A0001 ...和Z0001..I的帐户名称将此arraylist传递给api,需要使用Z200过滤名称并从列表中删除而不使用其他集合类。 以下是我的课程
class Account {
private String accountName;
private long accountNumber;
private String accountType;
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public long getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(long accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
}
public class GenericTest {
public static List filterObjects(List accountList) {
return list;
}
public static void main(String[] args) {
List<Account> accList = new ArrayList<Account>();
Account acc1 = new Account("A0001", 898989, "Savings");
Account acc2 = new Account("A0002", 345126, "Current");
Account acc3 = new Account("Z0001", 123467, "Savings");
Account acc4 = new Account("Z0002", 879000, "Fixed");
Account acc5 = new Account("Z0003", 898989, "Current");
accList.add(acc1);
accList.add(acc2);
accList.add(acc3);
accList.add(acc4);
accList.add(acc5);
GenericTest gt = new GenericTest();
List<Account> filteredList = gt.filterObjects(accList);
for (Account acc : filteredList) {
System.out.println(acc.getAccountName());
}
}
}
filterObjects api应该删除以Z开头的帐户对象并返回其他对象,而不使用api方法中的其他集合。我搜索了google和stackoverflow但没有找到合适的解决方案。请给我一些想法,这样我就可以工作了对那些人。提前谢谢。
答案 0 :(得分:3)
循环集合并删除以Z开头的元素:
public static List<Account> filterObjects(List<Account> accountList) {
for(int i = 0; i < accountList.size(); i++) {
if(accountList.get(i).getAccountName().startsWith("Z")) {
accountList.remove(i);
i--; // Just removed an element, so jump back one index.
}
}
return accountList;
}
或使用迭代器:
public static List<Account> filterObjects(List<Account> accountList) {
for (Iterator<Account> iterator = accountList.iterator(); iterator.hasNext();) {
Account account = iterator.next();
if (account.getAccountName().startsWith("Z")) {
iterator.remove();
}
}
}