Erik
Erik

Reputation: 335

Create sub-list and remove values from previous list

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

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);
     }
}    

Upvotes: 6

Views: 14469

Answers (5)

Blair Nangle
Blair Nangle

Reputation: 1541

The following will return a view of the original list, while removing the elements of the view from the original list:

List<Object> sublistViewOfOrginal = original.subList(0, n);
original.subList(0, n).clear();

To use the view as a list (with access to the usual List API methods), construct a concrete ArrayList from the view:

List<Object> actualListAsPortionOfOriginal = new ArrayList<>(sublistViewOfOrginal);

Upvotes: 0

naveejr
naveejr

Reputation: 735

Do it in a single line

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

Upvotes: 3

Bohemian
Bohemian

Reputation: 424983

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

Upvotes: 1

Mustafa Gen&#231;
Mustafa Gen&#231;

Reputation: 2579

Why dont you just do :

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

Upvotes: 1

BobTheBuilder
BobTheBuilder

Reputation: 19284

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.

Upvotes: 10

Related Questions