Monday, January 2, 2012

Loop through a list and modify it easily - JAVA ListIterator

Sample code:


        List<Integer> l = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++)
            l.add(Integer.valueOf(i));
        for (Integer j : l) {
            if (j > 0)
                System.out.print(", ");
            System.out.print(j);
        }
        System.out.println();
        ListIterator<Integer> lit = l.listIterator();
        while (lit.hasNext()) {
            Integer i = lit.next();
            if (i % 2 == 0)
                lit.remove();
            else
                lit.set(i + 10);
        }
        for (Integer j : l) {
            if (j > 11)
                System.out.print(", ");
            System.out.print(j);
        }

and the result will be


0, 1, 2, 3, 4, 5, 6, 7, 8, 9
11, 13, 15, 17, 19

No comments:

Post a Comment