Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sets vs Lists Alphabetical order in java

Tags:

java

list

set

Arent Lists a Ordered Collection, and Sets arent ordered? Then Why does this program sorts the String in Alphabetical order with Sets but not Lists? I understand the duplicates parts of the two.

    PrintStream out = System.out;

    List<String> set = new ArrayList<String>();
    String s = "ILLUSIONS";

    for(int i = 0; i< s.length(); i++)
    {
        set.add((new Character(s.charAt(i))).toString());

    }
    out.println(set);

outputs: ILLUSIONS


    PrintStream out = System.out;

    Set<String> set = new TreeSet<String>();
    String s = "ILLUSIONS";

    for(int i = 0; i< s.length(); i++)
    {
        set.add((new Character(s.charAt(i))).toString());

    }
    out.println(set);

outputs: ILNOSU

like image 510
user193113 Avatar asked Nov 23 '25 16:11

user193113


2 Answers

Lists are "ordered" by element index. That means they retain the order of insertion of elements. Sets (in general) do not retain such an order. Some exceptions:

  • The TreeSet is a particular Set, that keeps its elements in a naturally "sorted" order.
  • The LinkedHashSet is a particular Set, that does retain the insertion order.

If you want to "order" your list, you'll have to do that manually:

Collections.sort(list);

In fact, by "sorting" a list, you will re-arrange all list element indexes. See the relevant Javadoc on Collections.sort()

like image 180
Lukas Eder Avatar answered Nov 25 '25 07:11

Lukas Eder


When you say a List is ordered, it really just means that the lists preserve the order in which the element were inserted and the order in which they can be retrieved is predictable.

A Set is not ordered, its focus is just to have unique elements. A TreeSet is a SortedSet which along with maintaining uniqueness, also maintains elements in a sorted order. And hence the result that you see above

like image 34
aishwarya Avatar answered Nov 25 '25 08:11

aishwarya