Collections
Collections
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);
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.*;
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.
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.
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.
import java.util.*;
Let's see an example to traverse ArrayList elements using the Iterator interface.
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
}
}
Let's see an example to traverse the ArrayList elements using the for-each loop
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
for(String fruit:list)
System.out.println(fruit);
The get() method returns the element at the specified index, whereas the set() method changes the
element.
import java.util.*;
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
System.out.println("Returning element: "+al.get(1));//it will return the 2nd element, because index
starts from 0
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);
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{
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
Collections.sort(list1);
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
Collections.sort(list2);
for(Integer number:list2)
System.out.println(number);
import java.util.*;
class ArrayList7{
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add(1, "Gaurav");
al2.add("Sonoo");
al2.add("Hanumat");
//Adding second list elements to the first list
al.addAll(al2);
al3.add("John");
al3.add("Rahul");
al.addAll(1, al3);
import java.util.*;
class ArrayList8 {
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add("Anuj");
al.add("Gaurav");
al.remove("Vijay");
al.remove(0);
System.out.println("After invoking remove(index) method: "+al);
al2.add("Ravi");
al2.add("Hanumat");
al.addAll(al2);
al.removeAll(al2);
al.clear();
import java.util.*;
class ArrayList9{
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al2.add("Ravi");
al2.add("Hanumat");
al.retainAll(al2);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
import java.util.*;
class ArrayList10{
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After Insertion");
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;
//Creating Books
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
import java.util.*;
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());
import java.util.*;
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
ll.add(1, "Gaurav");
ll2.add("Sonoo");
ll2.add("Hanumat");
ll3.add("John");
ll3.add("Rahul");
ll.addAll(1, ll3);
ll.addFirst("Lokesh");
ll.addLast("Harsh");
import java.util.*;
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");
ll.remove("Vijay");
ll.remove(0);
ll2.add("Ravi");
ll2.add("Hanumat");
ll.addAll(ll2);
ll.removeAll(ll2);
ll.removeFirst();
ll.removeLast();
ll.removeFirstOccurrence("Gaurav");
ll.clear();
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]
import java.util.*;
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
Iterator i=ll.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
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;
//Creating Books
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
Self-Learning Exercise:
https://www.javatpoint.com/difference-between-arraylist-and-linkedlist
https://www.javatpoint.com/java-list
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.
import java.util.*;
class HashSet1{
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());
class HashSet2{
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());
import java.util.*;
class HashSet3{
set.add("Ravi");
set.add("Vijay");
set.add("Arun");
set.add("Sumit");
set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
set.removeAll(set1);
set.removeIf(str->str.contains("Vijay"));
set.clear();
import java.util.*;
class HashSet4{
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
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;
//Creating Books
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing HashSet
for(Book b:set){
Output: