You are on page 1of 20

The Set Interface

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set
abstraction. The Set interface contains only methods inherited from Collection and adds the
restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior
of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if
their implementation types differ. Two Set instances are equal if they contain the same elements.

The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and
LinkedHashSet. HashSet, which stores its elements in a hash table, is the best-performing
implementation; however it makes no guarantees concerning the order of iteration. TreeSet, which
stores its elements in a red-black tree, orders its elements based on their values; it is substantially
slower than HashSet. LinkedHashSet, which is implemented as a hash table with a linked list running
through it, orders its elements based on the order in which they were inserted into the set
(insertion-order).

Here's a simple but useful Set idiom. Suppose you have a Collection, c, and you want to create
another Collection containing the same elements but with all duplicates eliminated. The following
one-liner does the trick.
Collection<Type> noDups = new HashSet<Type>(c);

Set Interface Basic Operations

The size operation returns the number of elements in the Set (its cardinality). The isEmpty method
does exactly what you think it would. The add method adds the specified element to the Set if it is
not already present and returns a boolean indicating whether the element was added. Similarly, the
remove method removes the specified element from the Set if it is present and returns a boolean
indicating whether the element was present. The iterator method returns an Iterator over the Set.

The following program prints out all distinct words in its argument list.
import java.util.*;

public class FindDups {


public static void main(String[] args) {
Set<String> s = new HashSet<String>();
for (String a : args)
s.add(a);
System.out.println(s.size() + " distinct words: " + s);
}
}

Now run either version of the program.

java FindDups i came i saw i left

The following output is produced:

4 distinct words: [left, came, saw, i]


Note that the code always refers to the Collection by its interface type (Set) rather than by its
implementation type. This is a strongly recommended programming practice because it gives you
the flexibility to change implementations merely by changing the constructor.

Set Interface Bulk Operations


Bulk operations are particularly well suited to Sets; when applied, they perform standard set-algebraic
operations. Suppose s1 and s2 are sets. Here's what bulk operations do:

 s1.containsAll(s2) — returns true if s2 is a subset of s1. (s2 is a subset of s1 if set s1 contains all of
the elements in s2.)
 s1.addAll(s2) — transforms s1 into the union of s1 and s2. (The union of two sets is the set
containing all of the elements contained in either set.)
 s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2. (The intersection of two sets is
the set containing only the elements common to both sets.)
 s1.removeAll(s2) — transforms s1 into the (asymmetric) set difference of s1 and s2. (For example,
the set difference of s1 minus s2 is the set containing all of the elements found in s1 but not in s2.)

To calculate the union, intersection, or set difference of two sets nondestructively (without modifying either
set), the caller must copy one set before calling the appropriate bulk operation. The following are the
resulting idioms.

Set<Type> union = new HashSet<Type>(s1);


union.addAll(s2);

Set<Type> intersection = new HashSet<Type>(s1);


intersection.retainAll(s2);

Set<Type> difference = new HashSet<Type>(s1);


difference.removeAll(s2);

The List Interface


A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In
addition to the operations inherited from Collection, the List interface includes operations for the following:

 Positional access — manipulates elements based on their numerical position in the list. This
includes methods such as get, set, add, addAll, and remove.
 Search — searches for a specified object in the list and returns its numerical position. Search
methods include indexOf and lastIndexOf.
 Iteration — extends Iterator semantics to take advantage of the list's sequential nature.
The listIterator methods provide this behavior.
 Range-view — The sublist method performs arbitrary range operations on the list.

The Java platform contains two general-purpose List implementations. ArrayList, which is usually the
better-performing implementation, and LinkedList which offers better performance under certain
circumstances.

Collection Operations

The operations inherited from Collection all do about what you'd expect them to do, assuming you're
already familiar with them. If you're not familiar with them from Collection, now would be a good time to
read The Collection Interface section. The remove operation always removes the first occurrence of the
specified element from the list. The add and addAll operations always append the new element(s) to
the end of the list. Thus, the following idiom concatenates one list to another.

list1.addAll(list2);

Here's a nondestructive form of this idiom, which produces a third List consisting of the second list
appended to the first.

List<Type> list3 = new ArrayList<Type>(list1);


list3.addAll(list2);
Positional Access and Search Operations

The basic positional access operations are get, set, add and remove. (The set and remove operations return
the old value that is being overwritten or removed.) Other operations (indexOf and lastIndexOf) return the
first or last index of the specified element in the list.

The addAll operation inserts all the elements of the specified Collection starting at the specified position.
The elements are inserted in the order they are returned by the specified Collection's iterator. This call is
the positional access analog of Collection's addAll operation.

Here's a little method to swap two indexed values in a List.

public static <E> void swap(List<E> a, int i, int j) {


E tmp = a.get(i);
a.set(i, a.get(j));
a.set(j, tmp);
}

import java.util.*;

public class Shuffle {


public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (String a : args)
list.add(a);
Collections.shuffle(list, new Random());
System.out.println(list);
}
}

Iterating ArrayList using Iterator

Let's see an example to traverse ArrayList elements using the Iterator interface.

import java.util.*;

public class ArrayListExample2{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Traversing list through Iterator

Iterator itr=list.iterator();//getting the Iterator

while(itr.hasNext()){//check if iterator has the elements

System.out.println(itr.next());//printing the element and move to next

}
}

Iterating ArrayList using For-each loop

Let's see an example to traverse the ArrayList elements using the for-each loop

import java.util.*;

public class ArrayListExample3{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Traversing list through for-each loop

for(String fruit:list)

System.out.println(fruit);

Get and Set ArrayList

The get() method returns the element at the specified index, whereas the set() method changes the
element.

import java.util.*;

public class ArrayListExample4{

public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();

al.add("Mango");

al.add("Apple");

al.add("Banana");
al.add("Grapes");

//accessing the element

System.out.println("Returning element: "+al.get(1));//it will return the 2nd element, because index
starts from 0

//changing the element

al.set(1,"Dates");

//Traversing list

for(String fruit:al)

System.out.println(fruit);

How to Sort ArrayList

The java.util package provides a utility class Collections which has the static method sort(). Using the
Collections.sort() method, we can easily sort the ArrayList.

import java.util.*;

class SortArrayList{

public static void main(String args[]){

//Creating a list of fruits

List<String> list1=new ArrayList<String>();

list1.add("Mango");

list1.add("Apple");

list1.add("Banana");

list1.add("Grapes");

//Sorting the list

Collections.sort(list1);

//Traversing list through the for-each loop

for(String fruit:list1)

System.out.println(fruit);

System.out.println("Sorting numbers...");

//Creating a list of numbers


List<Integer> list2=new ArrayList<Integer>();

list2.add(21);

list2.add(11);

list2.add(51);

list2.add(1);

//Sorting the list

Collections.sort(list2);

//Traversing list through the for-each loop

for(Integer number:list2)

System.out.println(number);

Java ArrayList example to add elements

Here, we see different ways to add an element.

import java.util.*;

class ArrayList7{

public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();

System.out.println("Initial list of elements: "+al);

//Adding elements to the end of the list

al.add("Ravi");

al.add("Vijay");

al.add("Ajay");

System.out.println("After invoking add(E e) method: "+al);

//Adding an element at the specific position

al.add(1, "Gaurav");

System.out.println("After invoking add(int index, E element) method: "+al);

ArrayList<String> al2=new ArrayList<String>();

al2.add("Sonoo");

al2.add("Hanumat");
//Adding second list elements to the first list

al.addAll(al2);

System.out.println("After invoking addAll(Collection<? extends E> c) method: "+al);

ArrayList<String> al3=new ArrayList<String>();

al3.add("John");

al3.add("Rahul");

//Adding second list elements to the first list at specific position

al.addAll(1, al3);

System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+al);

Java ArrayList example to remove elements

Here, we see different ways to remove an element.

import java.util.*;

class ArrayList8 {

public static void main(String [] args)

ArrayList<String> al=new ArrayList<String>();

al.add("Ravi");

al.add("Vijay");

al.add("Ajay");

al.add("Anuj");

al.add("Gaurav");

System.out.println("An initial list of elements: "+al);

//Removing specific element from arraylist

al.remove("Vijay");

System.out.println("After invoking remove(object) method: "+al);

//Removing element on the basis of specific position

al.remove(0);
System.out.println("After invoking remove(index) method: "+al);

//Creating another arraylist

ArrayList<String> al2=new ArrayList<String>();

al2.add("Ravi");

al2.add("Hanumat");

//Adding new elements to arraylist

al.addAll(al2);

System.out.println("Updated list : "+al);

//Removing all the new elements from arraylist

al.removeAll(al2);

System.out.println("After invoking removeAll() method: "+al);

//Removing elements on the basis of specified condition

al.removeIf(str -> str.contains("Ajay")); //Here, we are using Lambda expression

System.out.println("After invoking removeIf() method: "+al);

//Removing all the elements available in the list

al.clear();

System.out.println("After invoking clear() method: "+al);

Java ArrayList example of retainAll() method

import java.util.*;

class ArrayList9{

public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();

al.add("Ravi");

al.add("Vijay");

al.add("Ajay");

ArrayList<String> al2=new ArrayList<String>();

al2.add("Ravi");

al2.add("Hanumat");
al.retainAll(al2);

System.out.println("iterating the elements after retaining the elements of al2");

Iterator itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Java ArrayList example of isEmpty() method

import java.util.*;

class ArrayList10{

public static void main(String [] args)

ArrayList<String> al=new ArrayList<String>();

System.out.println("Is ArrayList Empty: "+al.isEmpty());

al.add("Ravi");

al.add("Vijay");

al.add("Ajay");

System.out.println("After Insertion");

System.out.println("Is ArrayList Empty: "+al.isEmpty());

Java ArrayList Example: Book

Let's see an ArrayList example where we are adding books to list and printing all the books.

import java.util.*;

class Book {

int id;

String name,author,publisher;

int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {

this.id = id;

this.name = name;

this.author = author;

this.publisher = publisher;

this.quantity = quantity;

public class ArrayListExample20 {

public static void main(String[] args) {

//Creating list of Books

List<Book> list=new ArrayList<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to list

list.add(b1);

list.add(b2);

list.add(b3);

//Traversing list

for(Book b:list){

System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

Java LinkedList Example

import java.util.*;

public class LinkedList1{

public static void main(String args[]){


LinkedList<String> al=new LinkedList<String>();

al.add("Ravi");

al.add("Vijay");

al.add("Ravi");

al.add("Ajay");

Iterator<String> itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Java LinkedList example to add elements

Here, we see different ways to add elements.

import java.util.*;

public class LinkedList2{

public static void main(String args[]){

LinkedList<String> ll=new LinkedList<String>();

System.out.println("Initial list of elements: "+ll);

ll.add("Ravi");

ll.add("Vijay");

ll.add("Ajay");

System.out.println("After invoking add(E e) method: "+ll);

//Adding an element at the specific position

ll.add(1, "Gaurav");

System.out.println("After invoking add(int index, E element) method: "+ll);

LinkedList<String> ll2=new LinkedList<String>();

ll2.add("Sonoo");

ll2.add("Hanumat");

//Adding second list elements to the first list


ll.addAll(ll2);

System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ll);

LinkedList<String> ll3=new LinkedList<String>();

ll3.add("John");

ll3.add("Rahul");

//Adding second list elements to the first list at specific position

ll.addAll(1, ll3);

System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+ll);

//Adding an element at the first position

ll.addFirst("Lokesh");

System.out.println("After invoking addFirst(E e) method: "+ll);

//Adding an element at the last position

ll.addLast("Harsh");

System.out.println("After invoking addLast(E e) method: "+ll);

Java LinkedList example to remove elements

Here, we see different ways to remove an element.

import java.util.*;

public class LinkedList3 {

public static void main(String [] args)

LinkedList<String> ll=new LinkedList<String>();

ll.add("Ravi");

ll.add("Vijay");

ll.add("Ajay");

ll.add("Anuj");

ll.add("Gaurav");
ll.add("Harsh");

ll.add("Virat");

ll.add("Gaurav");

ll.add("Harsh");

ll.add("Amit");

System.out.println("Initial list of elements: "+ll);

//Removing specific element from arraylist

ll.remove("Vijay");

System.out.println("After invoking remove(object) method: "+ll);

//Removing element on the basis of specific position

ll.remove(0);

System.out.println("After invoking remove(index) method: "+ll);

LinkedList<String> ll2=new LinkedList<String>();

ll2.add("Ravi");

ll2.add("Hanumat");

// Adding new elements to arraylist

ll.addAll(ll2);

System.out.println("Updated list : "+ll);

//Removing all the new elements from arraylist

ll.removeAll(ll2);

System.out.println("After invoking removeAll() method: "+ll);

//Removing first element from the list

ll.removeFirst();

System.out.println("After invoking removeFirst() method: "+ll);

//Removing first element from the list

ll.removeLast();

System.out.println("After invoking removeLast() method: "+ll);

//Removing first occurrence of element from the list

ll.removeFirstOccurrence("Gaurav");

System.out.println("After invoking removeFirstOccurrence() method: "+ll);

//Removing last occurrence of element from the list


ll.removeLastOccurrence("Harsh");

System.out.println("After invoking removeLastOccurrence() method: "+ll);

//Removing all the elements available in the list

ll.clear();

System.out.println("After invoking clear() method: "+ll);

Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit, Ravi, Hanumat]

After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh, Amit]

After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]

After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav, Harsh]

After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]

After invoking clear() method: []

Java LinkedList Example to reverse a list of elements

import java.util.*;

public class LinkedList4{

public static void main(String args[]){

LinkedList<String> ll=new LinkedList<String>();

ll.add("Ravi");

ll.add("Vijay");

ll.add("Ajay");

//Traversing the list of elements in reverse order

Iterator i=ll.descendingIterator();

while(i.hasNext())

{
System.out.println(i.next());

Java LinkedList Example: Book

import java.util.*;

class Book {

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

this.id = id;

this.name = name;

this.author = author;

this.publisher = publisher;

this.quantity = quantity;

public class LinkedListExample {

public static void main(String[] args) {

//Creating list of Books

List<Book> list=new LinkedList<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to list

list.add(b1);

list.add(b2);

list.add(b3);
//Traversing list

for(Book b:list){

System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

Self-Learning Exercise:

https://www.javatpoint.com/difference-between-arraylist-and-linkedlist

https://www.javatpoint.com/java-list

Java HashSet Example

Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.

import java.util.*;

class HashSet1{

public static void main(String args[]){

//Creating HashSet and adding elements

HashSet<String> set=new HashSet();

set.add("One");

set.add("Two");

set.add("Three");

set.add("Four");

set.add("Five");

Iterator<String> i=set.iterator();

while(i.hasNext())

System.out.println(i.next());

Java HashSet example ignoring duplicate elements

In this example, we see that HashSet doesn't allow duplicate elements.


import java.util.*;

class HashSet2{

public static void main(String args[]){

//Creating HashSet and adding elements

HashSet<String> set=new HashSet<String>();

set.add("Ravi");

set.add("Vijay");

set.add("Ravi");

set.add("Ajay");

//Traversing elements

Iterator<String> itr=set.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Java HashSet example to remove elements

Here, we see different ways to remove an element.

import java.util.*;

class HashSet3{

public static void main(String args[]){

HashSet<String> set=new HashSet<String>();

set.add("Ravi");

set.add("Vijay");

set.add("Arun");

set.add("Sumit");

System.out.println("An initial list of elements: "+set);

//Removing specific element from HashSet

set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);

HashSet<String> set1=new HashSet<String>();

set1.add("Ajay");

set1.add("Gaurav");

set.addAll(set1);

System.out.println("Updated List: "+set);

//Removing all the new elements from HashSet

set.removeAll(set1);

System.out.println("After invoking removeAll() method: "+set);

//Removing elements on the basis of specified condition

set.removeIf(str->str.contains("Vijay"));

System.out.println("After invoking removeIf() method: "+set);

//Removing all the elements available in the set

set.clear();

System.out.println("After invoking clear() method: "+set);

An initial list of elements: [Vijay, Ravi, Arun, Sumit]

After invoking remove(object) method: [Vijay, Arun, Sumit]

Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]

After invoking removeAll() method: [Vijay, Arun, Sumit]

After invoking removeIf() method: [Arun, Sumit]

After invoking clear() method: []

Java HashSet from another Collection

import java.util.*;

class HashSet4{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();

list.add("Ravi");

list.add("Vijay");

list.add("Ajay");
HashSet<String> set=new HashSet(list);

set.add("Gaurav");

Iterator<String> i=set.iterator();

while(i.hasNext())

System.out.println(i.next());

Vijay

Ravi

Gaurav

Ajay

Java HashSet Example: Book

Let's see a HashSet example where we are adding books to set and printing all the books.

import java.util.*;

class Book {

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

this.id = id;

this.name = name;

this.author = author;

this.publisher = publisher;

this.quantity = quantity;

public class HashSetExample {


public static void main(String[] args) {

HashSet<Book> set=new HashSet<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

//Adding Books to HashSet

set.add(b1);

set.add(b2);

set.add(b3);

//Traversing HashSet

for(Book b:set){

System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

Output:

101 Let us C Yashwant Kanetkar BPB 8

102 Data Communications & Networking Forouzan Mc Graw Hill 4

103 Operating System Galvin Wiley 6

You might also like