Create a new array based on another array, but without the repeated data

1

As the title says, I am trying to create a second array based on an original array, but issuing the values that are repeated.

My problem is that the code does not work as I would expect, since whatever I do I can not generate the new array without repeating it successfully.

I thank you in advance.

Code:

String[] ape = new String[]{"Acevedo","Uribe","Osorio","Uribe","Acevedo","Correa","Milan"};
String[] nuevosApellidos= new String[ape.length];
    String temp="";
    int c=0;
    for(int k=0;k<e;k++){
        nuevosApellidos[c]= ape[k];
        temp= nuevosApellidos[c];
        List<String> iterador = Arrays.asList(nuevosApellidos);
        if(k>1){
            if(iterador.contains(temp)){
                System.out.println("El apellido "+temp+" ya estaba en el arreglo");
                if((k+1)<nuevosApellidos.length)nuevosApellidos[c]= ape[k+1];
                nuevosApellidos[c]="Vacío";
            }
        }
        c++;
    }
    
asked by carlos puello 09.04.2018 в 04:11
source

1 answer

1

Following the logic of your implementation, call a couple of things:

  • You always assign the value of a last name to the new arrangement, even though could be repeated: nuevosApellidos[c]= ape[k]
  • Just check if you have repeated for k > 1 so you could have k=0 and k=1 repeated.
  • It does not matter if the next if is fulfilled or not, you always overwrite it on the next line.

    if((k+1)<nuevosApellidos.length)nuevosApellidos[c]= ape[k+1];
    nuevosApellidos[c]="Vacío"
    

Instead:

  • You should only assign the new arrangement if it is not repeated
  • If repeated, you could assign "Vacío" or simply not increase the counter c

    for (int k = 0; k < e; k++) {
        temp = ape[k];
        List<String> iterador = Arrays.asList(nuevosApellidos);
        if (iterador.contains(temp)) {
            System.out.println("El apellido " + temp + " ya estaba en el arreglo");
            nuevosApellidos[c] = "Vacío";
        } else {
            nuevosApellidos[c] = temp;
        }
        c++;
    }
    
answered by 09.04.2018 / 05:38
source