我有一个ArrayList,其输出如下:
[, bd33b056-7a24-490f-a4bb-88cb2687facb%1514759804437%New York, USA%Florida, USA%2018-01-01%2018-01-10%UM-66%3050.0, bd33b056-7a24-490f-a4bb-88cb2687facb%1514759837907%New York, USA%California, USA%2018-01-01%2018-01-10%UM-66%8770.0]
现在我正在创建一个方法,将字符串id作为参数,当与预订ID匹配时,它将删除该索引。 id是在第一个%之后,有没有办法找出特定预订的索引? 这是方法
public static void removeElement(String id) throws FileNotFoundException, IOException{
BufferedReader b = new BufferedReader(new FileReader("Booking.dat"));
String d = b.readLine();
String[] allB = d.split("£");
ArrayList<String> data = new ArrayList<String>(Arrays.asList(allB));
data.remove(id);// need to have specific index of id inside the full arraylist
System.out.println(data);
}
答案 0 :(得分:1)
您可以使用removeIf
删除包含指定ID的元素:
data.removeIf(e -> e.contains(id));
如果你想在开头和结尾删除id只有%
的元素,那么你可以这样做:
data.removeIf(e -> e.contains("%"+id+"%"));
答案 1 :(得分:1)
我不确定为什么你坚持使用索引,因为stream会更有效率,但是这个方法按照请求获取索引并删除该元素:
public static void removeElement(String id) {
BufferedReader b = new BufferedReader(new FileReader("Booking.dat"));
String d = b.readLine();
String[] allB = d.split("£");
ArrayList<String> data = new ArrayList<String>(Arrays.asList(allB));
// Variable to save the index to. Set to -1 in case the index does not exist.
int index = -1;
for (int i = 0; i < data.size(); i++) { // Iterate through data
// Check if this index contains the id
if (data.get(i).contains(id)) {
index = i; // If it matches save the index and break
break;
}
}
if (index == -1) // If the index was never saved, return.
return;
data.remove(index);
System.out.println(data);
}