1

Here is my code for arrayList ,

 String[] n = new String[]{"google","microsoft","apple"};
      final List<String> list =  new ArrayList<String>();
      Collections.addAll(list, n);

how to remove all the elements that containslefrom the above list.
Is there any default method or by looping we have to remove manually.tell me how to do it.Thanks.

2
  • what is le? theres no le in the list Commented Oct 12, 2013 at 6:55
  • goole,apple here i want to remove this 'le' specific string from list elements Commented Oct 12, 2013 at 6:57

5 Answers 5

3

From java 8 You can use

list.removeIf(s -> s.contains("le"));
Sign up to request clarification or add additional context in comments.

Comments

2

use the following code.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class RemoveElements {

    /**
     * @param args
     */
    public static void main(String[] args) {
         String[] n = new String[]{"google","microsoft","apple"};
          List<String> list =  new ArrayList<String>();
          Collections.addAll(list, n);
          System.out.println("list"+list);
          Iterator<String> iter = list.iterator();
          while(iter.hasNext()){
              if(iter.next().contains("le"))
                  iter.remove();
          }

          System.out.println("list"+list);
    }

}

Comments

0

Part of javadoc for List:

/**
 * Removes the first occurrence of the specified element from this list,
 * if it is present (optional operation).  If this list does not contain
 * the element, it is unchanged...
boolean remove(Object o);

I hope this is what you are looking for.

Comments

0

Why to add and then remove ?

Check before adding.

    String[] n = new String[]{"google","microsoft","apple"};
     final List<String> list =  new ArrayList<String>();
     for (String string : n) {
         if(string.indexOf("le") <0){
            list.add(string);
        }
    }

That add's only one element microsoft to the list.

Comments

0

Yes, you have to loop from all the values in the list,
This may help you,

    String[] array  = new String[]{"google","microsoft","apple"};
    List<String> finallist =  new ArrayList<String>();
    for (int i = array.length -1 ; i >= 0 ; i--) 
    {
        if(!array[i].contains("le"))
            finallist.add(array[i]);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.