Find equal Strings of an ArrayList?

3

I have a three-color Array, Red, Blue and Green, with a while I add 10 random colors to an ArrayList. I need to find all the colors "Red", "Blue" and "Green" of the ArrayList, and then add all the "Red" colors found to an array where only "Red" colors will be stored, same with the other Strings. How do I do it? Thanks in advance.

public static void main(String[] args) {
    String[] colores = {"Rojo","Azul","Verde"};

    ArrayList<String> listaColores = new ArrayList<>();

    int numeroColores = 0;        
    while(numeroColores < 10){

    int random = (int)(Math.random() * 3);
    String color = colores[random];

    listaColores.add(color);

    numeroColores++;
    }
    
asked by Cheesse 02.11.2018 в 18:31
source

1 answer

1

I would in your case create a function that receives your ArrayList as a parameter and search among those colors. For that, I go through the whole array and I ask for each position what the color is. It is clear, that the arrangements of colors you would have to have created previously.

public void filtrarColores(ArrayList<String> colores){
  for (int i = 0; i < colores.size(); i++) {
    //asumo q los arreglos con colores los tenes creados antes de llamar a esta funcion
    switch (colores.get(i)) {
      case "Rojo":    
        colorRojo.add(colores[i]);
        break;
      case "Azul":    
        colorAzul.add(colores[i]);
        break;
      case "Verde":    
        colorVerde.add(colores[i]);
        break;
    }
  }
}

What is not clear to me is because you want a code like that, that is, the color arrangements would all be loaded with the same type of color, the only functionality that can be extracted is to do a colorAzul.length() for know how many blues you had, but you do not need to create an array for that. Quietly you can instead of adding color to an arrangement, you can keep a variable that is cantidadAzules and add 1 each time you find a blue one.

    
answered by 02.11.2018 / 19:02
source