You can use Set
that does not allow duplicates.
Set<String> disciplinas = new HashSet<>(Arrays.asList(disciplina));
disciplina = disciplinas.toArray(new String[disciplinas.size()]);
Set
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals (e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
Free translation:
A collection that does not contain duplicate items. More formally, sets do not contain pairs of elements e1 and e2 in case of e1.equals (e2). As the name suggests, this interface is an abstraction of the mathematical model "set".
A suggestion for resolution without using Collection
:
public String[] removerDuplicados(String[] base) {
String[] resultado = new String[base.length];
int contador = 0;
boolean encontrado;
for (int i = 0; i < base.length; i++) {
String elemento = base[i];
encontrado = false;
for (int j = 0; j < resultado.length; j++) {
if (resultado[j] == null) {
break;
}
if (resultado[j].equals(elemento)) {
encontrado = true;
}
}
if (!encontrado) {
resultado[contador] = elemento;
contador++;
}
}
return Arrays.copyOfRange(resultado, 0, contador);
}
Another way is to sort array
and then just compare to the previous record to insert into another, without the duplicates:
public String[] removerDuplicados(String[] base) {
String[] resultado = new String[base.length];
String anterior = null;
int indice = 0;
Arrays.sort(base);
for (String atual : base) {
if (atual != null && (anterior == null || !atual.equals(anterior))) {
resultado[indice] = atual;
indice++;
}
anterior = atual;
}
return Arrays.copyOfRange(resultado, 0, indice);
}
Apply the above two methods as follows:
disciplina = removerDuplicados(disciplina);