Remove specific string from arraylist elements containing a particular subsrtring

后端 未结 5 616
我寻月下人不归
我寻月下人不归 2021-01-24 15:00

Here is my code for arrayList ,

 String[] n = new String[]{\"google\",\"microsoft\",\"apple\"};
      final List list =  new ArrayList

        
相关标签:
5条回答
  • 2021-01-24 15:40

    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);
        }
    
    }
    
    0 讨论(0)
  • 2021-01-24 15:42

    From java 8 You can use

    list.removeIf(s -> s.contains("le"));
    
    0 讨论(0)
  • 2021-01-24 15:44

    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.

    0 讨论(0)
  • 2021-01-24 15:51

    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]);
        }
    
    0 讨论(0)
  • 2021-01-24 16:03

    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.

    0 讨论(0)
提交回复
热议问题