1

I have an ArrayList whose output is given as:

[, 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]

Now I am creating a method to have a string id as parameter, when ever is matches with the id of booking it will remove that index. The id is after first %, is there any way to find out index of that specific booking? Here is method

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);
}

2 Answers2

1

You can remove the elements that contain the specified id with removeIf:

data.removeIf(e -> e.contains(id));

if you want to remove elements where the id only has % at the beginning and at the end then you can do:

data.removeIf(e -> e.contains("%"+id+"%"));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

I am not sure why you insist of having the index, because streams would be much more efficient, but this method gets the index as requested and removes that element:

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);
}
Cardinal System
  • 2,749
  • 3
  • 21
  • 42