Fill ArrayList Without repeating the values

0

Good I am new here in this page, My problem is the following one, although I am sure that it will be simple for you; I have an ArrayList with a number of N sellers that can or can not be repeated, but I want to pass said vendor to another ArrayList without these being repeated.

For example; If in the seller ArrayList we have {Pedro, Lucas, Juan, Jose, Pedro, Robinson, Jose, Lucas} or Repeated

The ArrayList2 must be {Pedro, Lucas, Juan, Jose, Robinson} Not repeated

Here I have the code with which I try to do it but it does not work as I want, since when executing it only shows Robinson and Jhon.

public class Testings {

public static void main(String[] args) {

    ArrayList<Vendedor> vendedor = new ArrayList<Vendedor>();
    ArrayList<Vendedor> juntados = new ArrayList<Vendedor>();

    vendedor.add(new Vendedor("Robinson", 0, 0, 0));
    vendedor.add(new Vendedor("Jhon", 0, 0, 0));
    vendedor.add(new Vendedor("Robinson", 0, 0, 0));
    vendedor.add(new Vendedor("Pedro", 0, 0, 0));
    vendedor.add(new Vendedor("Juan", 0, 0, 0));
    vendedor.add(new Vendedor("Cristian", 0, 0, 0));
    vendedor.add(new Vendedor("Pedro", 0, 0, 0));
    vendedor.add(new Vendedor("Cristian", 0, 0, 0));
    vendedor.add(new Vendedor("Juan", 0, 0, 0));

    boolean user = false;

    for (int u = 0; u < vendedor.size(); u++) {

        if (juntados.size() <= 0) {

            juntados.add(vendedor.get(u));

        } else {

            for (int y = 0; y < juntados.size(); y++) {

                if (vendedor.get(u).getNombre().equals(juntados.get(y).getNombre())) {

                    user = true;

                }

            }

            if (user == false) {

                juntados.add(vendedor.get(u));
            }

        }

    }

    for (Vendedor indice : juntados) {

        System.out.println(indice.getNombre());

    }

}

}

    
asked by Robinson Daniel 13.05.2018 в 23:47
source

2 answers

0

A small mistake: you must reinitialize user to false before searching for the seller u in the list of juntados .

Since you do not reinitialize it to false , once you find the first match you set it to true , you never change it again and you discard all other values.

In any case I advise you to familiarize yourself with the Java debugger, which allows you to run the program line by line and see the value of the expressions, so you can see where the program stops doing what you expect.

    
answered by 13.05.2018 в 23:53
0

Within your seller class you need to generate the hashcode and equals methods (the IDES can generate them automatically).

Then applying a bit of functional programming ...

    juntados = (ArrayList<Vendedor>) vendedor.stream().distinct().collect(Collectors.toList());
    
answered by 14.05.2018 в 04:45