Java Arraylist remove multiple element by index

后端 未结 8 1579
后悔当初
后悔当初 2020-12-19 06:54

Here is my code:

for (int i = 0; i < myarraylist.size(); i++) {
        for (int j = 0; j < stopwords.size(); j++) {
            if (stopwords.get(j).e         


        
8条回答
  •  醉酒成梦
    2020-12-19 07:10

    Using ListIterator

    ArrayList list = new ArrayList();
          // List : ["java", ".net", "javascript", "html", "css", "selenium", "image", "Spring"]
    
        ArrayList indexes = new ArrayList();
                                          // indexes : [5, 3, 2, 5, 0]
        // Sort the Indexes in Order to remove from back words. and make Unique
        TreeSet uniqueSorted = new TreeSet();
            uniqueSorted.addAll(indexes);
    
        // To remove all elements from the ArrayList and make its size = 0  
            indexes.clear(); 
            indexes.addAll(uniqueSorted);
    
        // Iterate form back, so that if size decreases also no problem.
        ListIterator li = indexes.listIterator(indexes.size());
    
       // we can traverse a List in both the directions (forward and Backward).
            while(li.hasPrevious()) {
                int position = li.previous();
                list.remove(position);
            }
    

提交回复
热议问题