Thursday, 23 May 2019

Java: Ordered vs sorted collection


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]


You may like

No comments:

Post a Comment