Catch all elements that meet a condition

2

I have some Vector :

public static Vector<Integer> id = new Vector<Integer>();
public static Vector<String> nome = new Vector<String>();
public static Vector<String> nascimento = new Vector<String>();
public static Vector<String> trabalho = new Vector<String>();
public static Vector<String> foto = new Vector<String>();
public static Vector<String> premios = new Vector<String>();

I'm currently using the following code to fetch a value in these arrays :

if(where.equals("id"))
    key = Record.id.indexOf(Integer.parseInt(value));
else if(where.equals("nome"))
    key = Record.nome.indexOf(value);
else if(where.equals("nascimento"))
    key = Record.nascimento.indexOf(value);
else if(where.equals("trabalho"))
    key = Record.trabalho.indexOf(value);
else if(where.equals("foto"))
    key = Record.foto.indexOf(value);
else if(where.equals("premios"))
    key = Record.premios.indexOf(value);

The problem is that in the case, indexOf finds only the first occurrence in the list, I want to get the index of all occurrences of an element, is there any native method of Java for this? Or just using for and putting the found indexes in a new Vector ?

    
asked by anonymous 15.06.2016 / 16:11

1 answer

2

If you are using java 8, you can use the streams API and pass a predicate and return the elements that meet a certain condition, follow the code below:

public List<String> obtemFotos(String criterio) {
  return Record.fotos
    .stream()
    .filter(foto -> foto.equals(criterio))
    .collect(Collectors.toList())
}

It would be something along these lines, and you would do this for each collection of yours, I think it has a much better way of handling those vectors case by case, but I will not go into that because it goes beyond the scope of this question.     

15.06.2016 / 18:18