Home » Java » Java create subList and remove values from previous List

Java create subList and remove values from previous List

Posted by: admin December 28, 2021 Leave a comment

Questions:

I want to create a subList in Java and remove values that are in subList from the previous List. My program correctly creates subList, but than it doesn’t remove the correct values from previousList.

My Code:

for(int i=0; i<4; i++){
     List<Object> sub=new ArrayList<Object>(prevoiusList.subList(0,6));

     for (int j=0; j<6; j++){
         previousList.remove(j);
     }
}    
Answers:

At first j=0 and you remove the first element. When doing so you shift all other elements, so the second element becomes first and so on.

On next iteration j=1, so you remove the second element, which was originally the third…

In order to fix this issue, use only 0 index, or an iterator.

###

Do it in a single line

prevoiusList.subList(0,6).clear()

###

Why dont you just do :

previousList = previousList.subList(7, previousList.size());

###

To “move” 6 elements from one list to create another list:

List<Object> list;
List<Object> subList = new ArrayList<Object>(list.subList(0, 6));
list.removeAll(subList);

It should be noted that List.subList(), returns a view of the list, so modifications to the origianl list will be reflected in the sub list, hence creating the new list and passing the sub list to the constructor.

To put this in a loop:

List<Object> list;
while (list.size() > 5) {
    List<Object> subList = new ArrayList<Object>(list.subList(0, 6));
    list.removeAll(subList);
    // do something with subList
}
// list now has 0-5 elements