2017-12-31 169 views
2

で特定のサブ文字列を持っている場合、私は、その出力として与えられているのArrayListを持っているフル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は最初の%の後です。特定の予約のインデックスを見つける方法はありますか?あなたはidはほんの始まりに%を持っている要素を削除したい場合は

data.removeIf(e -> e.contains(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

あなたがマップウィッヒを使用することができますのでArrayListのために提供されるサンプル・データ与えられたあなたは、各要素 –

+0

のキーを持つことができます。 'removeElement'メソッドのサンプル入力をいくつか提供して、要素を削除した後でArrayListに含めると予想されるものを記述できますか? –

+0

それはちょうど私ですが、この質問は[XY問題](http://xyproblem.info/)ishと感じています。 –

答えて

1

あなたはremoveIfで指定されたidが含まれている要素を削除することができますです

data.removeIf(e -> e.contains("%"+id+"%")); 
+0

ありがとうございました!長い間これを探していた –

+0

@ JordanRanen probs、解決があなたを助けてくれてうれしい。 –

1

なぜインデックスを持っているのかわかりませんficientが、この方法が要求されるように、インデックスを取得し、その要素を削除します。

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