Vote Up 0 Vote Down

Use different ways to iterate over a List

We would like to know how to use different ways to iterate over a List.

answer


Vote Up 0 Vote Down
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/*  ww  w.javascrapbook.com/getanswer*/
public class Main {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<Integer>();

    for (Integer i : Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7))
      numbers.add(i);
    printList(numbers); // 0,1,2,3,4,5,6,7

    // replaces each element with twice its value
    for (int index = 0; index < numbers.size(); index++) {
      numbers.set(index, numbers.get(index) * 2);
    }
    printList(numbers);

    // does nothing because list is not being changed
    for (Integer number : numbers) {
      number++;
    }
    printList(numbers); 

    // same as above -- just different syntax
    for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext();) {
      Integer number = iter.next();
      number++;
    }
    printList(numbers);

    for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext();) {
      Integer number = iter.next();
      iter.add(number + 1);
    }
    printList(numbers);

    for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext();) {
      Integer number = iter.next();
      if (number % 2 == 0) // if number is even
        iter.remove(); // remove it from the collection
    }
    printList(numbers); // 1,3,5,7,9,11,13,15

    // ListIterator<?> has a "set" method to replace elements
    for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext();) {
      Integer number = iter.next();
      iter.set(number / 2); // divide each element by 2
    }
    printList(numbers); // 0,1,2,3,4,5,6,7

    // Use Java 8 Lambda
    List<Integer> list = numbers;
    list.stream().forEach(elem -> System.out.println("element " + elem));

  }

  public static void printList(List<Integer> numbers) {
    System.out.println(numbers);
  }
}
flag | link

your answer

Who Are You?

Have an account already? Login before answering!