My question is how can I find a string that is repeated within an arralist? I am making a system that is able to search any file name repeated within a specified route, to do this I lift everything on the route and charge it in ArrayList<String>
with the following method.
ArrayList<String> arrayArchivos = new ArrayList<>();
public void buscarArchivo(File ruta) {
// Creo el vector que contendra todos los archivos de una ruta especificada.
File[] archivo = ruta.listFiles();
// Evaluo si la carpeta especificada contiene archivos.
if (archivo != null) {
arrayArchivos.clear();
// Recorro el vector el cual tiene almacenado la ruta del archivo a buscar.
for (int i = 0; i < archivo.length; i++) {
// Evaluo si el archivo o la ruta es una carpeta.
if (archivo[i].isDirectory()) {
// Le paso la nueva ruta de la carpeta si se cambia la ruta e busca nuevamente.
buscarArchivo(archivo[i]);
} else {
arrayArchivos.add(archivo[i].getName());
}
}
evaluarNombre();
}
}
In the method evaluateName ()
public void evaluarNombre2() {
// Evaluo si el array esta vacio.
if (arrayArchivos != null) {
// Recorremos el array
for (String arrayArchivo : arrayArchivos) {
// Mostramos solo letras y espacios ya que las cadenas a buscar pueden contener
// num y caracteres especiales.
String a = arrayArchivo.replaceAll("[^a-zA-Z ]", "").trim();
// Partimos la cadena donde encuentre un espacio.
String[] arraStrings = a.split(" ");
// Llamamos al metodo contar() pasandole por parametro un arreglo.
contar(arraStrings);
}
} else {
System.out.println("No se encontro ningun archivo.");
}
}
Method count ()
private void contar(String[] arraStrings) {
// Declaramos un contador.
int c = 0;
// Nos posicionamos en un elemento y recorremos el resto comparando.
for (int i = 0; i < arraStrings.length - 1; i++) {
for (int j = i + 1; j < arraStrings.length; j++) {
// Si los nombres de las cadenas son iguales, el contador se ingrementa.
if (arraStrings[i].substring(0, arraStrings[i].lastIndexOf("")).equals(arraStrings[j].substring(0, arraStrings[j].lastIndexOf("")))) {
c++;
}
}
// Evaluo que el contador sea mayor a 1.
if (c > 1) {
System.out.println("El archivo '" + arraStrings[i] + "' Se repite " + c);
}
}
}
The files I post in the arraylist are these
In this case, they are just mp3 file names but is applicable to any file type is meant? The output I get is
But as you can see in the first image, only the file
02. - Maluma - Corazon - Dexter Remix (Global Music11) - copy
Is it the one that is repeated, what am I doing wrong? I would really appreciate your help, thank you very much.