You can use the Set
which 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 Uplicate 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.
In free translation:
A collection that does not contain duplicate items. More formally, sets do not contain pairs of E1 and E2 elements in case of E1.equals(E2). As the name suggests, this interface is an abstraction of the mathematical model "set".
A resolution suggestion 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 order the array
and then just compare with the previous record to insert into one 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);
Both are
ArrayList
ofString
?– Costamilam
are not arraylists, I am not using Collections, only arrays
– cicada 3301
Why You Can’t Use Collections?
– Victor Stafusa
It’s college exercise, probably.
– Gustavo Cinque
Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).
– Sorack