-6

I have an ArrayList like this:

[{1=R111, 2=Red, 3=50000}, {1=R123, 2=Blue , 3=50000}]

and i want to remove the array by value (R111 or R123).

how to remove the array using array.remove method for array like that?

I've try this link but it's doesn't work for my problem.

  • Possible duplicate of https://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java – Stefan Dec 19 '17 at 10:13
  • 4
    Possible duplicate of [How do I remove objects from an array in Java?](https://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java) – UserID0908 Dec 19 '17 at 10:15
  • 5 seconds on google would have found you this: [inline link](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-java.lang.Object-) – Old Nick Dec 19 '17 at 10:21
  • @Stefan no, it's different array. – Ananda Bayu Putra Yudhistira Dec 19 '17 at 10:38
  • Your question is not very clear. You have an `ArrayList` containing arrays and you want to remove an array from the `ArrayList` based on a value in the array? So your result would be `[{1=R123, 2=Blue , 3=50000}]` when you remove based on ` R111`? – Pieter Dec 19 '17 at 10:41
  • @Pieter yes, i want to remove the ArrayList based on a value. – Ananda Bayu Putra Yudhistira Dec 19 '17 at 10:54

2 Answers2

1

Assuming your ArrayList is this:

List<String[]> arrayList = new ArrayList<>();
arrayList.add(new String[]{"R111","Red","50000"});
arrayList.add(new String[]{"R123","Blue","50000"});

you can do something like:

for (Iterator<String[]> iterator = arrayList.iterator();iterator.hasNext();) {
    String[] stringArray = iterator.next();
    if("R111".equals(stringArray[0])) {
        iterator.remove();
    }
}

You can safely remove an element using iterator.remove() while iterating the ArrayList. Also see The collection Interface.

An alternative shorter approach using Streams would be:

Optional<String[]> array = arrayList.stream().filter(a -> "R111".equals(a[0])).findFirst();
array.ifPresent(strings -> arrayList.remove(strings));
Pieter
  • 895
  • 11
  • 22
1

Thanks pieter, I used Iterator like this:

for (Iterator<HashMap<String, String>> iterator = RegulerMenu.iterator(); iterator.hasNext();) {
    HashMap<String, String> stringArray = iterator.next();
            if("R111".equals(stringArray.get("1"))) {
                iterator.remove();
            }
        }

It's work now, Thankyou verymuch.