How to remove all elements from List except specific?

UPDATED: 25 November 2014
Collection Framework Java

retainAll(Collection<?> c)
Retains only the elements in this list that are contained in the specified collection. In other words, removes elements from list which is not available in specified list.

Source Code
import java.util.ArrayList;
import java.util.List;

/**
 * @author javaQuery
 */
public class RetainListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add element from 0th position */
        listString.add("a");
        listString.add("b");
        listString.add("c");
        listString.add("d");
        listString.add("e");

        /* Print list */
        System.out.println("Initial List:\n" + listString);
        System.out.println("---------------------------------");

        /* Create another list of String */
        List<String> retainList = new ArrayList<String>();
        /* Add elements that you want to keep in final List */
        retainList.add("b");
        retainList.add("d");

        /* Call `retainAll(Collection<?> c)` and pass list of item you want to keep */
        listString.retainAll(retainList);

        /* Print list */
        System.out.println("List after retainAll(Collection<?> c):\n" + listString);
    }
}

Output
Initial List:
[a, b, c, d, e]
---------------------------------
List after retainAll(Collection<?> c):
[b, d]

0 comments :