o7planning

Java Collections Framework Tutorial with Examples

  1. Introduction
  2. First example
  3. The limitations of using arrays - A suggestion to solve the problem.
  4. Oveview of Java Collections Framework
  5. Collection Group
  6. Map group

1. Introduction

Collection is a basic idea of program and language. An application often works with collection, for example the storage of information of employees, collection of images, etc. Like other language, Java also support array as a most basic collection. However, working with array is not convenient in many situations because in the lifetime of array, the increase in elements or elimination of elements is very difficult, even pays the price for the efficiency of the program if it is intentional.
The image below illustrates an array:

2. First example

First, we have an example with LinkedList. It is a list whose number of elements is changeable without limit as that of array.
HelloLinkedList.java
package org.o7planning.tutorial.javacollection.helloworld;

import java.util.LinkedList;

public class HelloLinkedList {

	public static void main(String[] args) {
		// Create LinkedList object.
		LinkedList<String> list = new LinkedList<String>();

		// Add elements to the linked list.
		list.add("F");
		list.add("B");
		list.add("D");
		list.add("E");
		list.add("C");

		// Add the specified element to the end of this list.
		list.addLast("Z");

		// Add the specified element to the beginning of this list.
		list.addFirst("A");

		// Inserts the specified element at position with index 1.
		list.add(1, "A2");

		// Print out, all elements
		System.out.println("Original contents of list: " + list);

		// Remove a element from the linked list
		list.remove("F");

		// Remove the element at index 2.
		list.remove(2);

		// Print out the list, after removing two elements.
		System.out.println("Contents of list after deletion: " + list);

		// Remove first and last elements.
		list.removeFirst();
		list.removeLast();

		// Print out collection after removing.
		System.out.println("List after deleting first and last: " + list);

		// Get element at index 2.
		Object val = list.get(2);

		// Set element at index 2.
		list.set(2, (String) val + " Changed");
		System.out.println("List after change: " + list);
	}

}
Results of running the example:
Original contents of list: [A, A2, F, B, D, E, C, Z]
Contents of list after deletion: [A, A2, D, E, C, Z]
List after deleting first and last: [A2, D, E, C]
List after change: [A2, D, E Changed, C]
An example with HashMap. This is an object containing pairs of key/value. Considering a telephone book, a telephone number is a key while the information of subscriber is a value. Keys must not be the same.
HelloHashMap.java
package org.o7planning.tutorial.javacollection.helloworld;

import java.util.HashMap;

public class HelloHashMap {

	public static void main(String[] args) {

		// Create a HashMap objects, store pairs of employee-code and salary.
		// String key: Employee-code
		// Float value: Salary
		HashMap<String, Float> salaryMap = new HashMap<String, Float>();
	 

		salaryMap.put("E01", 1000f);
		salaryMap.put("E02", 12000f);
		salaryMap.put("E03", 12300f);
		salaryMap.put("E04", 1000f);
		salaryMap.put("E05", 300.5f);
		
		// Get the salary of employee 'E02'
		Float salary= salaryMap.get("E01");
		System.out.println("Salary of employee E01 = "+ salary);
		
		// Update the salary for employee 'E05'		
		salaryMap.put("E05", 400f);
		
		System.out.println("Salary of employee E05 = "+ salaryMap.get("E05"));
		 
	}

}
Results of running the example:
Salary of employee E01 = 1000.0
Salary of employee E05 = 400.0

3. The limitations of using arrays - A suggestion to solve the problem.

Array - a basic collection type.
  • Array is very basic and familiar.
    • storing the reference type, primitive type
    • int[] myArray=new int[]{1,4,3};
    • Object[] myArrayObj =new Object[]{"Object",new Integer(100)};
  • Arrays have fixed sizes and dimensions.
    • This makes it difficult to expend an array
  • Elements are arranged and referenced sequentially in memory.
    • This makes it difficult to remove an element from the array.
Remove element from array
Elements of an array are continuously arranged in the memory, so it is difficult if you intentionally remove an element in the array because it will lose the continuation. Typically, a technique is to create a new array storing objects of the previous array and discard unnecessary elements, but this reduce the efficiency of the program. A similar technique is applied to the array expansion, in which we create a new array with a bigger size, and then copy elements of the previous array to the new array.

Obviously, array is not a good way in many situations of application.
Linked List
The Linked List is one of data management ways that overcomes weaknesses of array. Of course, there are various ways of managing list in Java, for example ArrayList

Let's see features of LinkedList:
  • Elements in this list can be discontinuously isolated in the memory.
  • It is a two-way link between elements.
    • Each element in the list makes a reference to the opposing element in front of it and the element right behind it.
LinkedList is a two-way link.
Link element is a object containing data you need to manage. It has two references to Link elements in front of and behind it.
Like a group of people in queue, each person needs to remember two people standing right in front of and behind his/her.
Remove an element from LinkedList
Remove an element from LinkedList is the same as eliminating a person who are standing in a queue. Two people adjacent to this person have to reupdate the information of people in front of and behind them.
Add element to LinkedList (Add at the end or in middle of the list)
In short, although we just have an example of a linked list, it helps us understand java.util package much more.
Note: LinkedList is one of solutions to array's weaknesses. ArrayList is a way of managing data collection. It can deal with array's weaknesses, but the way it manages data is different from LinkedList's.

4. Oveview of Java Collections Framework

Being aware of limitations of arrays from the version 1.0, java has java.util.Vector, is a class storing list of objects. And java.util.Hashtable is a class storing pairs of key/value. Next, Java2 platform continues to introduce ways of approaching collections, named as Collections Framework. java.util.Vector, java.util.Hashtable still exist and now are part of that huge platform. These collections are built on the basis of some interfaces in java.util package. They are divided into 2 hierarchical system led by 2 interfaces java.util.Collection containing the list of objects and java.util.Map containing pairs of key/value.
Interfaces in Java Collections Framework
The above image is important interface of Java Collections Framework.We will talk about the using purpose of those interfaces and group them by purpose and usage. In java.util package, classes implement one or many these interfaces. Thus, a class in java.util may have many different functions. For example java.util.HashMap:
** Hashtable **
public class HashMap<K,V> extends AbstractMap<K,V>
                           implements Map<K,V>, Cloneable, Serializable
** Vector **
public class Vector<E> extends AbstractList<E>
            implements List<E>, RandomAccess, Cloneable, Serializable
Two hierarchy led by 2 interface Collection and Map - Data Storage Methods
  • Collection group stores objects.
    • There are three sub-branch in Collection group: Queue, List, and Set.
    • Elements may be either similar or not, depending on their branch. (More details are discussed later).
  • Map group stores pairs of key and value
    • The key in the Map are not allowed the same.
    • If we know the key, we can extract the value equivalent to its key in Map.
Collection group stores data in the form of reference types while Map group stores pairs of key and value.
Collection<String> c=new ArrayList<String>();
// Add element to collection.
c.add("One");


Map<Integer,String> m=new LinkedHashMap<Integer,String>();
Integer key=new Integer(123);
String value="One two three";

// Add a pair of 'key/value' to Map m.
// If 'key' already exists, 'value' will be replaced by new value.
m.put(key,value);

// Print out the value corresponding to the key
System.out.println(m.get(new Integer(123));
Interfaces Iterator and RandomAccess - Data Access Methods
  • java.util.Iterator
    • Is a iterator to retrieve data, visiting in turn from this element to another element.
  • java.util.RandomAccess
    • Method of random access, for example to position elements and retrieve that element in the set
    • For instance, java.util.Vector implements this interface, can retrieve random element vector.get (int index).
  • The Collection group can also access in turn by calling method iterator() to retrieve the Iterator object.
    • java.util.Collection extending from java.lang.Iterable interface, so it inherited public Iterator<E> iterator() method, the iterator over elements of Collection.
On the illustration above 2 Interface Iterator & RandomAccess, it represents two ways to access the elements in a collection.
See Vector class:
** Vector **
public class Vector<E> extends AbstractList<E>
               implements List<E>, RandomAccess, Cloneable, Serializable
Vector belong to the Collection group , you can access its elements through Iterator and also random access through get (index) method.

Note: For classes in the List group, you can also retrieve the ListIterator object, this iterator allows you backward or forward the cursor position on the list instead of may only forward as of the Iterator.

5. Collection Group

The interfaces in the Collection group
Three direct sub-interface of Collection are Queue, List and Set. In which, Queue is added from 1.5 version and considered a waiting queue. Queue also has a sub-interface, BlockingQueue, which belongs to java.util.concurrent package, but we don't discuss it in this lesson. Queue is a interface containing many definitions and the way of organizing elements we need to pay most attention to. Three interface Queue , List , Set are regarded as three branches of Collection group. Before moving on the details of each group, let's see the overview of Collection interface.
java.util.Collection Interface
Inheritance relationship
** java.util.Collection **
public interface Collection<E> extends java.lang.Iterable<E> {

   //
   // Add element to collection
   // return true if this collection changed as a result of the call
   //
   boolean add(E o);

   //
   // Adds all of the elements in the specified collection to this collection.
   // return true if this collection changed as a result of the call
   //
   boolean addAll(Collection<? extends E> c);

   // Removes all of the elements from this collection (optional operation).
   // The collection will be empty after this method returns.
   void clear();

   // Returns true if this collection contains the specified element.
   boolean contains(Object o);

   // Returns true if this collection contains all of the elements
   // in the specified collection.
   boolean containsAll(Collection<?> c);

   // Compares the specified object with this collection for equality
   boolean equals(Object o);

   int hashCode();

   // Returns true if this collection contains no elements.
   boolean isEmpty();

   //
   // Removes a single instance of the specified element from this
   // collection, if it is present (optional operation).
   //
   boolean remove(Object o);

   // Removes all of this collection's elements that are also contained in the
   // specified collection (optional operation)
   boolean removeAll(Collection<?> c);

   //
   // Retains only the elements in this collection that are contained in the
   // specified collection (optional operation)
   //
   boolean retainAll(Collection<?> c);

   // Returns the number of elements in this collection
   int size();

   // Returns an array containing all of the elements in this collection
   Object[] toArray();

   <T> T[] toArray(T[] a);

   // Returns an iterator over the elements in this collection.
   Iterator<E> iterator();
}
Access the elements of the collection
An iterator over the elements in the collection.
For example, using the iterator to access the collection's elements.
CollectionAndIterator.java
package org.o7planning.tutorial.javacollection.collection;

import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

public class CollectionAndIterator {

	public static void main(String[] args) {

		// Create empty collection.
		// A Collection containing only String.
		Collection<String> coll = new Vector<String>();
		coll.add("Collection");
		coll.add("Queue");
		coll.add("List");
		coll.add("Map");

		// Print out the number of elements in this collection.
		System.out.println("Size:" + coll.size());

		// Returns an iterator over the elements in this collection.
		// This Iterator containing only String.
		Iterator<String> ite = coll.iterator();

		// Check if Iteractor has next element or not?
		while (ite.hasNext()) {
			// Get the element at the position of the cursor.
			// Then move the cursor one step further.
			String s = ite.next();
			System.out.println("Element:" + s);
		}
	}

}
Results of running the example:
Size:4
Element:Collection
Element:Queue
Element:List
Element:Map
The branch of the Collection
As said above, Collection has three sub-interface including Queue , List and Set. The difference among them is the way of storing data.
java.util.Queue
java.util.List
java.util.Set
Allow contain duplicate elements
Allow contain duplicate elements
Do not allow duplicate elements
Not allowed contain null elements
Allow contains one or more null elements
Depending on the class implements Set interface, supported contain null element or not. If supported, It contains only at most one null element.
List
A List is an ordered list of objects, where the same object may well appear more than once. For example: [1, 7, 1, 3, 1, 1, 1, 5]. It makes sense to talk about the "N th" in a list. You can add an element anywhere in the list, change an element anywhere in the list, or remove an element from any position in the list.
Queue
A Queue is also ordered, but you'll only ever touch elements at one end. All elements get inserted at the "end" and removed from the "beginning" (or head) of the queue. You can find out how many elements are in the queue, but you can't find out what, say, the "third" element is. You'll see it when you get there.
Set
A Set is not ordered and cannot contain duplicates. You again can't ask for the "N th" element or even the "first" element, since they are not in any particular order. You can add or remove elements, and you can find out if a certain element exists (e.g., "is 7 in this set?")
java.util.List Interface
List is a sub-interface of Collection. It owns full of features of Collection, along with some special features:
  • Allow duplicate elements
  • Allow zero or many null elements to exist.
  • A list is an ordered list of objects
In addition to accessing by using Iterator, we can access by using ListIterator. ListIterator allows moving forward or backward the cursor.
// Returns a list iterator over the elements in this list  
public ListIterator<E> listIterator()  
 
// Returns a ListIterator over the elements in this list 
// (in proper sequence),
// starting at the specified position in the list..
public ListIterator<E> listIterator(int index)
ListAndListIterator.java
package org.o7planning.tutorial.javacollection.list;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ListAndListIterator {

	public static void main(String[] args) {

		// Create List object (Containing only String).
		List<String> list = new ArrayList<String>();
		list.add("One");
		list.add("Two");
		list.add("Three");
		list.add("Four");


		ListIterator<String> listIterator = list.listIterator();

		// Currently the cursor at the first position of the Iterator.
		// (Index 0).
		// Get the first element in the interator, the cursor forward one step.
		String first = listIterator.next();
		System.out.println("first:" + first);// -->"One"

		// Current cursor at index 1
		// Get next element.
		String second = listIterator.next();
		System.out.println("second:" + second);// -->"Two"

		// Check if the cursor can jump back 1 step or not.
		if (listIterator.hasPrevious()) {
			// Go back one step.
			String value = listIterator.previous();
			System.out.println("value:" + value);// -->"Two"
		}

		System.out.println(" ----- ");

		while (listIterator.hasNext()) {
			String value = listIterator.next();
			System.out.println("value:" + value);
		}
	}

}
Results of running the example:
first:One
second:Two
value:Two
 -----
value:Two
value:Three
value:Four
java.util.Set Interface
Set is a sub-Interface of Collection. It owns full of features of Collection, along with some other features:
  • Describe a set that does not allow duplicate elements
  • Allow the existence of one null element, if any.
HashSetExample.java
package org.o7planning.tutorial.javacollection.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetExample {

	public static void main(String[] args) {

		// Create a Set object with initial capacity 10.
		// Automatically increase capacity 80% if the number of elements to
		// overcome the current capacity.
		// HashSet (LIFO - Last in first out)
		// (element to be added later will stand first).
		Set<String> set = new HashSet<String>(10, (float) 0.8);

		set.add("One");
		set.add("Two");

		// When Duplication occurs.
		// With HashSet: It will add new element, and remove the old element.
		set.add("One");
		set.add("Three");

		Iterator<String> it = set.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}

}
Results of running the example:
One
Two
Three
java.util.Queue Interface
Queue is a subtype Interface of Collection, it is full of features of the Collection, it is quite similar to the List, however, use purpose is slightly different. Queue is designed to only access the first element in the queue, and when removing elements, it will remove the first element of the queue. It's likely to line of people queuing at the supermarket, only the head of the queue will be served, newcomers will be inserted into the queue, inserted position may not the end of the line. The position of the inserted element depends on the type of queue and the priority of the element.
  • Queue allows elements to duplicate .
  • Do not allow null elements.
There are two classes implements the Queue interface.
  • java.util.LinkedList
  • java.util.PriorityQueue
LinkedList is a pretty standard queue implementation. But remember, LinkedList implement both List and Queue interface.

PriorityQueue stores its elements internally according to their natural order (if they implement Comparable), or according to a Comparator passed to the PriorityQueue.
Note that a class can implement both of List and Queue interfaces, so you do not need to care about how the elements arranged in the internal of above class, if you regarded it as a queue, please see the way to access the elements of the queue. Consider the typical method of Queue, it simulates queue likely line of people queuing at the supermarket.
Throws exception
Returns special value
Insert
add(e)
offer(e)
Remove
remove()
poll()
Examine
element()
peek()
boolean add(E)
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
boolean offer(E)
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception.
E remove()
Retrieves and removes the head of this queue. This method differs from poll only in that it throws an exception if this queue is empty.
E poll()
Retrieves, but does not remove, the head of this queue. This method differs from peek only in that it throws an exception if this queue is empty.
E element()
Retrieves, but does not remove, the head of this queue. This method differs from peek only in that it throws an exception if this queue is empty.
E peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
Comment:
There is no method among the queue methods mentioned above allows you to access other elements in the queue, except the first element, you also can not specify the location of element which will be inserted.
QueueDemo.java
package org.o7planning.tutorial.javacollection.queue;

import java.util.LinkedList;
import java.util.Queue;

public class QueueDemo {

	public static void main(String[] args) {

		Queue<String> names = new LinkedList<String>();

		// offer(E): Insert element to queue.
		// With LinkedList, element will inserted at the end of queue.
		// Return true if success.
		// Return false if queue full.
		names.offer("E");
		names.offer("A");
		names.offer("M");

		// add(E): Insert element to queue
		// With LinkedList, element will inserted at the end of queue.
		// Return true if success.
		// Throw exception if queue full.
		names.add("G");
		names.add("B");

		while (true) {
			// Retrieves and removes the head of this queue,
			// or returns null if this queue is empty.
			String name = names.poll();
			if (name == null) {
				break;
			}
			System.out.println("Name=" + name);
		}

	}

}
The results of running the example:
Name=E
Name=A
Name=M
Name=G
Name=B
For example with a priority queue PriorityQueue.This queue stores its elements internally according to their natural order (if they implement Comparable), or according to a Comparator passed to the PriorityQueue.
String is a class that implements the Comparable interface, and they can be compared with each other, and arranged in alphabetical order.
PriorityQueueDemo.java
package org.o7planning.tutorial.javacollection.queue;

import java.util.PriorityQueue;
import java.util.Queue;

public class PriorityQueueDemo {

	public static void main(String[] args) {

		// With PriorityQueue queue, the elements will be arranged on the natural order.
		Queue<String> names = new PriorityQueue<String>();

		// offer(E): Insert element to queue.
		// Return true if success
		// Return false if queue is full.
		names.offer("E");
		names.offer("A");
		names.offer("M");

		// add(E): Insert element to queue.
		// Return true if success
		// Throw exception if queue is full.
		names.add("G");
		names.add("B");

		while (true) {
			// Retrieves and removes the head of this queue,
			// or returns null if this queue is empty.
			String name = names.poll();
			if (name == null) {
				break;
			}
			System.out.println("Name=" + name);
		}

	}

}
Results of running example:
Name=A
Name=B
Name=E
Name=G
Name=M
Inheritance relationships among classes in Collection Group
Some common classes:
Implementations
Hash Table
Resizable Array
Balanced Tree
Linked List
Hash Table + Linked List
Interfaces
Set
HashSet
TreeSet
LinkedHashSet
Interfaces
List
ArrayList
java.util.ArrayList
ArrayList owns full of features of Listinterface. In addition, it allows accessing to random elements due to the inheritance of RandomAccess.
It is basically similar to Vector class. However, while methods of Vector are synchronized, those of ArrayList are not. ArrayList is suitable for one-thread applications.
ArrayListDemo.java
package org.o7planning.tutorial.javacollection.list;

import java.util.ArrayList;

public class ArrayListDemo {

	public static void main(String[] args) {

		// Create an ArrayList object that contains the element of type Integer.
		ArrayList<Integer> list = new ArrayList<Integer>(10);

		// Add elements.
		list.add(123);
		list.add(245);
		list.add(new Integer(345));

		// ArrayList allow add null elements.
		// (Feature of List)
		list.add(null);

		// Print out the number of elements in this list.
		System.out.println("Size:" + list.size());// =4

		// Random access to elements of index 1.
		Integer i = list.get(1);
		System.out.println("Element index 1 =" + i);// =245
		Integer newInt = 1000;

		// Replaces the element at the index 1.
		// This method return old element.
		Integer old = list.set(1, newInt);
		// 
		System.out.println("Old value:" + old);// =245 .
		System.out.println("New value:" + list.get(1));// =1000 .
	}

}
Results of running the example:
Size:4
Element index 1 =245
Old value:245
New value:1000
java.util.Vector
Vector is a class whose functions is similar to ArrayList. The difference is that methods of Vector are synchronized while those of ArrayList are not.
Methods of Vector are synchronized, so it works well in Multiple Thread applications.
Vector has some additional methods which are inheritance of 1.0 version before the concept of Collection Framework is mentioned in Java.
Methods of Vector are synchronized, so it works well in Multiple Thread applications.
Vector has some additional methods which are inheritance of 1.0 version before the concept of Collection Framework is mentioned in Java.
// Legacy method from 1.0, get element at index position
// Like get(index)
public E elementAt(int index)


// Method inherited from the List interface, get element at position index.
public E get(int index)

// Replaces the element at the specified position in this list with the specified element
// Return old element.
// setElementAt(int,E) like set(int,E)
public void setElementAt(int index, E element);

// Replaces the element at the specified position in this list with the specified element
// Return old element.
public E set(int index, E element)
VectorDemo.java
package org.o7planning.tutorial.javacollection.list;

import java.util.Vector;

public class VectorDemo {

	public static void main(String[] args) {
		// Create Vector object with capacity 10 (element)
		// Automatically increase capacity 5,
		// if the number of elements to overcome the current capacity.
		Vector<Integer> v = new Vector<Integer>(10, 5);

		v.add(123);
		v.add(245);
		v.add(new Integer(345));
		v.add(null);

		// Print out the number of elements in this Vector. (Not capacity).
		System.out.println("Size:" + v.size());// =4

		// Get element at index 1
		// (Same as get(int) method)
		Integer i = v.elementAt(1);
		System.out.println("v.elementAt(1)=" + i);// 245


		v.setElementAt(1000, 1);
		// 
		System.out.println("New value:" + v.get(1));// =1000 .
	}
}
Results of running the example:
Size:4
v.elementAt(1)=245
New value:1000
java.util.SortedSet
SortedSet is a subtype interface of the the Set interface, it is full of the features of Set. SortedSet is a category of sets which have arrangements,new elements added to the category of sets automatically stand at a suitable position to ensure set still be arranged (ascending or descending).

Therefore, the elements of the SortedSet must be compared with each other, and they must be the object of java.lang.Comparable (Can be comparable). If you add an element which is not the object of Comparable to the SortedSet, you'll get an exception.
The Class implements SortedSet: TreeSet.
Consider class Player, includes the following information: name, number of of gold medals, number of silver medal, number of bronze medal.

Players can be compared with each other according to the principle:
  1. Who has more gold medals will rank higher.
  2. If two of the same number of gold medals, who has more silver medal will rank higher.
  3. If two people have the same number of gold and silver medals, who has more bronze medals than the other will rank higher.
  4. Others considered as same rank.
Class Player will implement java.lang.Comparable interface.
Player.java
package org.o7planning.tutorial.javacollection.sortedset;

public class Player implements Comparable<Player> {

	private String name;

	private int goldMedal;
	private int silverMedal;
	private int bronzeMedal;

	public Player(String name, int goldMedal, int silverMedal, int bronzeMedal) {
		this.name = name;
		this.goldMedal = goldMedal;
		this.silverMedal = silverMedal;
		this.bronzeMedal = bronzeMedal;
	}

	// Compare this player with other player
	// If return value < 0 means this player < other
	// If return value > 0 means this player > other
	// If return value = 0 means this player = other
	@Override
	public int compareTo(Player other) {
		// Compare the number of gold medals.
		int value = this.goldMedal - other.goldMedal;
		if (value != 0) {
			return value;
		}
		// Compare the number of silver medals.
		value = this.silverMedal - other.silverMedal;
		if (value != 0) {
			return value;
		}
		// Compare the number of bronze medals.
		value = this.bronzeMedal - other.bronzeMedal;
		return value;
	}

	@Override
	public String toString() {
		return "[" + this.name + ", Gold: " + this.goldMedal //
				+ ", Silver: " + this.silverMedal + ", Bronze: " //
				+ this.bronzeMedal + "]";
	}

}
SortedSetDemo.java
package org.o7planning.tutorial.javacollection.sortedset;

import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetDemo {

	public static void main(String[] args) {

		// Create a SortedSet object via the subclass TreeSet.
		SortedSet<Player> players = new TreeSet<Player>();

		Player tom = new Player("Tom", 1, 3, 5);
		Player jerry = new Player("Jerry", 3, 1, 3);
		Player donald = new Player("Donal", 2, 10, 0);

		// Add element to set
		// They will automatically be sorted (Ascending).
		players.add(tom);
		players.add(jerry);
		players.add(donald);

		// Print out elements
		for (Player player : players) {
			System.out.println("Player: " + player);
		}
	}

}
Results of running SortedSetDemo:
Player: [Tom, Gold: 1, Silver: 3, Bronze: 5]
Player: [Donal, Gold: 2, Silver: 10, Bronze: 0]
Player: [Jerry, Gold: 3, Silver: 1, Bronze: 3]

6. Map group

Interfaces in the Map group
Map group led by the java.util.Map interface. This interface has 2 children's interface are java.util.SortedMap and java.util.concurrent.ConcurrentMap. ConcurrentMap not belong to java.util package, it was introduced from version java1.5, we do not refer to it in this document. Map group characterized by storing data over the key/value pairs.
Classes in Map group
java.util.Map Interface
SN
Methods with Description
1
void clear( )

Removes all key/value pairs from the invoking map.(optional operation).

2
boolean containsKey(Object k)

Returns true if the invoking map contains k as a key. Otherwise, returns false.

3
boolean containsValue(Object v)

Returns true if the map contains v as a value. Otherwise, returns false

4
Set<Map.Entry<K,V>> entrySet( )

Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set-view of the invoking map.

5
boolean equals(Object obj)

Returns true if obj is a Map and contains the same entries. Otherwise, returns false.

6
Object get(K k)

Returns the value associated with the key k.

7
int hashCode( )

Returns the hash code for the invoking map.

8
boolean isEmpty( )

Returns true if the invoking map is empty. Otherwise, returns false.

9
Set<K> keySet( )

Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map.

10
Object put(K k, V v)

Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned.(optional operation).

11
void putAll(Map<? extends K,? extends V> m)

Puts all the entries from m into this map.(optional operation).

12
Object remove(Object k)

Removes the entry whose key equals k. (optional operation).

13
int size( )

Returns the number of key/value pairs in the map.

14
Collection values( )

Returns a collection containing the values in the map. This method provides a collection-view of the values in the map.

The optional methods (Optional operation), can be supported on its implementation class or not, If not supported, it can throw UnsupportedOperationException:
import java.util.Collection;
import java.util.Map;
import java.util.Set;

public class MyMap<K,V> implements Map<K,V>{

   .....
     
     // If you call this method, an exception will be thrown unconditionally.
    @Override
    public void clear() {
        throw new java.lang.UnsupportedOperationException();        
    }  

}
Thus, MyMap class does not support the real meaning of clear() method. If users intentionally use this method of MyMap, will receive an exception.
MapDemo.java
package org.o7planning.tutorial.javacollection.map;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapDemo {

	public static void main(String[] args) {

		Map<String, String> map = new HashMap<String, String>();

		map.put("01000005", "Tom");
		map.put("01000002", "Jerry");
		map.put("01000003", "Tom");
		map.put("01000004", "Donald");

		// Get a set view of the keys contained in this map.
		// This collection is not sorted.
		Set<String> phones = map.keySet();

		for (String phone : phones) {
			System.out.println("Phone: " + phone + " : " + map.get(phone));
		}

	}

}
Running results:
Phone: 01000004 : Donald
Phone: 01000003 : Tom
Phone: 01000005 : Tom
Phone: 01000002 : Jerry
You can access the data of Map through Map.Entry, see the illustration below:
MapEntryDemo.java
package org.o7planning.tutorial.javacollection.map;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class MapEntryDemo {

	public static void main(String[] args) {

		Map<String, String> map = new HashMap<String, String>();

		map.put("01000005", "Tom");
		map.put("01000002", "Jerry");
		map.put("01000003", "Tom");
		map.put("01000004", "Donald");

		// Get set of entries
		// This entry may not sort by key.
		Set<Entry<String, String>> entries = map.entrySet();

		for (Entry<String, String> entry : entries) {
			System.out.println("Phone: " + entry.getKey() + " : " + entry.getValue());
		}

	}
}
Running Results:
Phone: 01000004 : Donald
Phone: 01000003 : Tom
Phone: 01000005 : Tom
Phone: 01000002 : Jerry
java.util.SortedMap Interface
SortedMap is the sub-interface of Map. It ensures that the key/value pairs are arranged in ascending order according to the key.
There is only one class in java.util implements SortedMap interface, which is TreeMap.
The method of SortedMap:
SN
Methods with Description
1
Comparator comparator( )

Returns the invoking sorted map's comparator. If the natural ordering is used for the invoking map, null is returned.

2
Object firstKey( )

Returns the first key in the invoking map.

3
SortedMap headMap(Object end)

Returns a sorted map for those map entries with keys that are less than end.

4
Object lastKey( )

Returns the last key in the invoking map.

5
SortedMap subMap(Object start, Object end)

Returns a map containing those entries with keys that are greater than or equal to start and less than end

6
SortedMap tailMap(Object start)

Returns a map containing those entries with keys that are greater than or equal to start.

SortedMapDemo.java
package org.o7planning.tutorial.javacollection.sortedmap;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class SortedMapDemo {

	public static void main(String[] args) {

		Map<String, String> map = new TreeMap<String, String>();

		map.put("01000005", "Tom");
		map.put("01000002", "Jerry");
		map.put("01000003", "Tom");
		map.put("01000004", "Donald");

		// This set has been sorted in ascending.
		Set<String> keys = map.keySet();
		for (String key : keys) {
			System.out.println("Phone: " + key);
		}

		System.out.println("-----");

		// This set has been sorted in ascending.
		Set<Map.Entry<String, String>> entries = map.entrySet();
		for (Map.Entry<String, String> entry : entries) {
			System.out.println("Phone: " + entry.getKey());
		}
	}

}
The results of running the example:
Phone: 01000002
Phone: 01000003
Phone: 01000004
Phone: 01000005
-----
Phone: 01000002
Phone: 01000003
Phone: 01000004
Phone: 01000005