Java: Ordered vs sorted collection
A collection is a group of objects contained in a single object. The Java Collections Framework is a set of classes in java.util
for storing collections. There are four main interfaces in the Java Collections Framework.
List
: A list is an ordered collection of elements that allows duplicate entries. Elements in a list can be accessed by anint
index.Set
: A set is a collection that does not allow duplicate entries.Queue
: A queue is a collection that orders its elements in a specific order for processing. A typical queue processes its elements in a first‐in, first‐out order, but other orderings are possible.Map
: A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs.
Ordered collection maintains the elements in the order you inserted. List is an example of Ordered collection.
Sorted collection maintains the elements in sorted order. SortedSet, SortedMap are examples of Sorted collection.
App.java
package com.sample.app;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
public class App {
public static void main(String args[]) {
List<String> list = new ArrayList<>();
SortedSet<String> sortedSet = new TreeSet<>();
list.add("India");
list.add("Australia");
list.add("America");
list.add("Canada");
sortedSet.add("India");
sortedSet.add("Australia");
sortedSet.add("America");
sortedSet.add("Canada");
System.out.println("list : " + list);
System.out.println("sortedSet : " + sortedSet);
}
}
Output
list : [India, Australia, America, Canada]
sortedSet : [America, Australia, Canada, India]