In what order is a Set stored? Random?

6

When I store something inside a Set , the order in which it stores is random?

And how could I sort a Set ?

    
asked by anonymous 12.11.2014 / 15:59

3 answers

6

Set is just an interface. The order depends on the implementation.

The HashSet has no guarantee of order. In practice it is random.

The LinkedHashSet keeps the order in which the elements are inserted.

The TreeSet sorts the elements according to natural ordering (ascending, alphabetical, etc.). It is possible to pass a Comparator on the constructor to specify how it should sort if the natural ordering does not exist or is not what is desired.

In order to instantiate TreeSet with a Comparator , we can use a class to part, an anonymous class or a reference to a method (java 8):

With class apart:

public void instanciaElemento() {
    TreeSet<SuaClasse> = new TreeSet<>(new MeuComparator());
}

public static class MeuComparator implements Comparator<SuaClasse> {
    @Override
    public int compare(SuaClasse a, SuaClasse b) {
        // Implementação...
        // Retorna 1 se a é depois de b, -1 se a é antes de b ou 0 se os dois são iguais.
    }
}

With anonymous class:

public void instanciaElemento() {
    TreeSet<SuaClasse> = new TreeSet<>(new Comparator<> {
        @Override
        public int compare(SuaClasse a, SuaClasse b) {
            // Implementação...
            // Retorna 1 se a é depois de b, -1 se a é antes de b ou 0 se os dois são iguais.
        }
    });
}

Regarding Method:

public void instanciaElemento() {
    TreeSet<SuaClasse> = new TreeSet<>(EstaClasse::metodoComparador);
}

private static int metodoComparador(SuaClasse a, SuaClasse b) {
    // Implementação...
    // Retorna 1 se a é depois de b, -1 se a é antes de b ou 0 se os dois são iguais.
}
    
12.11.2014 / 16:06
6

While TreeSet sorts elements, the decision to use this implementation should not be made just in case you need to sort the list in a moment.

When instantiating a TreeSet , HashSet or LinkedHashSet you should consider the advantages of each, especially with regard to the cost to add and the cost to recover an element. Some implementations work best for adding multiple elements, others for retrieving elements, and all of that depends on the variety of objects placed inside.

If you simply have a set and want to generate an ordered list, just use the constructor of ArrayList which receives Collection any.

So:

Set<String> conjunto = new HashSet<>();
conjunto.add("Jose");
conjunto.add("Maria");
conjunto.add("Joao");
conjunto.add("Maria");
System.out.println(conjunto);

//conjunto -> lista
List<String> lista = new ArrayList<>(conjunto);
Collections.sort(lista);
System.out.println(lista);

IdeOne Example

    
12.11.2014 / 16:21
4

To complete @Victor's response

The set by itself does not save anything, since it is a Interface :

Article about set here >

Image:

  

InwhatorderisaSetstored?Random?

Yes

Example:

importjava.util.HashSet;publicclassHashSetExample{publicstaticvoidmain(Stringargs[]){//HashSetdeclarationHashSet<String>hset=newHashSet<String>();//AddingelementstotheHashSethset.add("Apple");
      hset.add("Mango");
      hset.add("Grapes");
      hset.add("Orange");
      hset.add("Fig");
      //Addition of duplicate elements
      hset.add("Apple");
      hset.add("Mango");
      //Addition of null values
      hset.add(null);
      hset.add(null);

      //Displaying HashSet elements
      System.out.println(hset);
    }
}

Output:

[null, Mango, Grapes, Apple, Orange, Fig]

link to this example

If you intend to make a Set of any object created by you, you should implement Comparable :

For example this for a class account:

public class Conta implements Comparable<Conta> {

    private int numero;
    private String titular;
    // outros metodos e atributos

    @Override
    public int compareTo(Conta outraConta) {
        if (this.numero < outraConta.numero) {
            return -1;
        }
        if (this.numero > outraConta.numero) {
            return 1;
        }
        return 0;
    }
} 

You have a good article here

    
12.11.2014 / 16:12