Java Set and List Simple Operation

I have made some operation on Set and List in Java, using addAll, removeAll, retainAll functionality. These functionality act like the mathematical set functions.

Now I proceed with the Java coding, you all can learn from here. Below the code will be the DOS-based output.

import java.util.*;

class Test8 {
    public static void main(String args[]) {
        Set setA = new HashSet();
        setA.add(1);
        setA.add(2);
        setA.add(3);
        setA.add(4);

        Set setB = new HashSet();
        setB.add(2);
        setB.add(4);
        setB.add(6);
        setB.add(8);

        System.out.println("Set A: " + setA);
        System.out.println("Set B: " + setB);

        Set addAllSet = new HashSet(setA);
        addAllSet.addAll(setB);
        System.out.println("Add All Operation: " + addAllSet);

        Set removeAllSet = new HashSet(setA);
        removeAllSet.removeAll(setB);
        System.out.println("Remove All Operation: " + removeAllSet);

        Set retainAllSet = new HashSet(setA);
        retainAllSet.retainAll(setB);
        System.out.println("Retain All Operation: " + retainAllSet);

        System.out.println("—————————–");

        List listA = new ArrayList();
        listA.add(1);
        listA.add(2);
        listA.add(3);
        listA.add(4);

        List listB = new ArrayList();
        listB.add(2);
        listB.add(4);
        listB.add(6);
        listB.add(8);

        System.out.println("List A: " + listA);
        System.out.println("List B: " + listB);

        List addAllList = new ArrayList(listA);
        addAllList.addAll(listB);
        System.out.println("Add All Operation: " + addAllList);

        List removeAllList = new ArrayList(listA);
        removeAllList.removeAll(listB);
        System.out.println("Remove All Operation: " + removeAllList);

        List retainAllList = new ArrayList(listA);
        retainAllList.retainAll(listB);
        System.out.println("Retain All Operation: " + retainAllList);
    }
}

image

Please note that, Set is unordered, and having unique elements, meant non-duplicate. List is ordered, and having redundant elements, meant duplicate is allowed.

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply