3

Example:

list1 = [10,20,30,40,50] size = 5

Based on size of list1=5 I need to remove last 5 elements from list2
list2 = [11,23,32,12,21,21]

Output = [11]

So if size of list1 is n I need to remove last n elements from list 2 ?
What is an efficient way to achieve this ?

user2789973
  • 197
  • 1
  • 3
  • 11
  • Do you want to alter existing list, or do you wan want to create new list with first `x` elements from list2, where `x=list2.size() - list1.size()`? – Pshemo Jan 25 '15 at 04:29

3 Answers3

7

You could consider using the subList(...) method of ArrayList.

Phil
  • 3,375
  • 3
  • 30
  • 46
3

You can create a while-loop, like this:

 List yourList = ...; // Your list
 int removed = 0; // Setup the variable for removal counting

 while (removed < Math.min(secondList.size(), 5)) { // While we still haven't removed 5 entries OR second list size
   yourList.remove(yourList.size() - 1); // Remove the last entry of the list
   removed++; // Increases 'removed' count
 }
2

Since your N = list1.length() index of first element from which we should start removing can be calculated as

/*
  list1:       3, 4, 5, 6 (length=4)
  list2: a, b, c, d, e, f (length=6)
               ^- element from which we start deleting, its index = 2 (6-4)
*/

int indexOfFirstElementToRemove = list2.size() - list1.size();

Note: we don't know if list1 will always be smaller than list2. If it is not then indexOfFirstElementToRemove would be negative or 0. In such case we need to remove all elements from list2 so calling list2.clear() is enough.

To remove elements while iterating we use Iterator or ListIterator (if available). To start iterating from specified index we can use

ListIterator<ElementType> iterator = listOfElements.listIterator(firstElementIndex);

So our final solution can look like:

List<Integer> list1 = Stream.of(2, 3, 4, 5).collect(Collectors.toList());
List<Integer> list2 = Stream.of(0, 1, 2, 3, 4, 5).collect(Collectors.toList());

int indexOfFirstElementToRemove = list2.size() - list1.size();

if (indexOfFirstElementToRemove > 0) {

    ListIterator<Integer> iterator = list2.listIterator(indexOfFirstElementToRemove);

    while (iterator.hasNext()) {
        iterator.next();
        iterator.remove();
    }

} else {//indexOfFirstElementToRemove<=0 so we need to remove all elements from list2
    list2.clear();
}
System.out.println(list2); //Output: [0, 1]
Pshemo
  • 122,468
  • 25
  • 185
  • 269