Write a method, downsize, that will remove every nth element from a LinkedList of employee names.
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList<String> staff = new LinkedList<String>();
staff.add("John");
staff.add("Bob");
staff.add("Richard");
staff.add("Alice");
staff.add("Jane");
staff.add("Carlos");
staff.add("Jose");
staff.add("Maria");
downsize(staff, 3);
System.out.println(staff);
System.out.println("Expected: [John, Bob, Alice, Jane, Jose, Maria]");
}
public static void downsize(LinkedList<String> employeeNames, int n)
{
ListIterator<String> iter = employeeNames.listIterator();
for(int i=n; i<employeeNames.size(); i++)
{
iter.next();
}
iter.remove();
}
}
I'm having some troubles to find a perfect loop that can remove any nth element in my ListIterator. thank you!
This will remove every n-th element from the employeeNames LinkedList:
for(int i=0; i<employeeNames.size(); i++)
{
iter.next();
if (i % n == 0) iter.remove();
}
Never ever modify a list that you are currently iterating over. That way madness lies.
public static List<String> downsize(List<String> employeeNames, int n) {
Set<String> employeesToRemove = new HashSet<String>();
for (int index = n; index < employeeNames.size(); index += n) {
employeesToRemove.add(employeeNames.get(index);
}
employeeNames.removeAll(employeesToRemove);
}
If, however, you absolutely must iterate over the array, here is that madness also.
public static List<String> downsize(List<String> employeeNames, int n) {
for (int index = employeeNames.size() - (n -(employeeNames.size() % n)) ; index >= 0; index -= n) {
employeeNames.remove(index);
}
return employeeNames;
}